From 0f206bfc29f1d521115053019d2d9b98ac597a6f Mon Sep 17 00:00:00 2001 From: shira Date: Mon, 5 Oct 2026 21:03:19 +0300 Subject: [PATCH 001/143] docs: document scaffold status and make local doc checks reproducible --- docs/en/DEPLOY.md | 2 +- docs/en/DEVELOPMENT.md | 43 ++++++++++++++++++++++ docs/ru/DEPLOY.md | 2 +- docs/ru/DEVELOPMENT.md | 43 ++++++++++++++++++++++ scripts/docs-check.py | 60 +++++++++++++++++++++++++++++-- scripts/test_docs_check.py | 67 ++++++++++++++++++++++++++++++++++- scripts/test_merge_schemas.py | 4 ++- 7 files changed, 214 insertions(+), 7 deletions(-) diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 6923c36..4fc4a94 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -15,7 +15,7 @@ The backend build context is `backend/`, so Docker applies `backend/.dockerignor The current `postgres:alpine` volume mounts at `/var/lib/postgresql`; the image stores data in a subdirectory for its major version. When the tag advances to a new major version, migrate an existing database with `pg_upgrade` or backup/restore. Updating the image alone does not convert the data. -Open http://127.0.0.1:8080. The host port binds to loopback. Nginx handles /healthz, proxies /api/ to Go, and uses the SPA fallback for other paths. The Go health endpoint is /api/v1/healthz; the internal Go /readyz checks PostgreSQL with SELECT 1, Redis with PING, and the SeaweedFS bucket with HeadBucket; any dependency being unavailable produces 503. The internal backend port 9090 serves /metrics. +Open http://127.0.0.1:8080. The host port binds to loopback. Nginx handles /healthz, proxies /api/ to Go, and uses the SPA fallback for other paths. The public API health route is /api/v1/healthz through Nginx /api/. On the internal port 8080, Go also serves /healthz for the process and /readyz, which checks PostgreSQL with SELECT 1, Redis with PING, and the SeaweedFS bucket with HeadBucket; any dependency being unavailable produces 503. The internal backend port 9090 serves /metrics. This Nginx configuration has no production TLS. The current bind does not expose the app directly to the public network. Remote access needs a selected TLS reverse proxy, firewall rules, and environment-specific configuration. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index 4faf082..2e3cdf1 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -13,6 +13,49 @@ This guide describes the current technical scaffold and the commands declared in Select current stable frontend dependency releases and keep pnpm-lock.yaml committed for repeatable installs. ML dependencies are locked in uv.lock; Go dependencies are in backend/go.mod. An update must change its lock/configuration and pass checks for that service. Container images use the requested moving `latest` or `alpine` tags; inspect their current Compose/Dockerfile references instead of treating the tag as a fixed version. +## Scaffold status + +The repository contains a verifiable technical scaffold, not a product. Values below are read from the named files; when updating a dependency, change its source and lockfile and update this table in both languages. + +| Component | Pinned version | Source | +| --- | --- | --- | +| Go | 1.26.8 (`go` directive; no separate `toolchain` line) | backend/go.mod; build image `golang:1.26.8-alpine` in backend/Dockerfile | +| Node.js | 26.10.0 | frontend/.node-version | +| pnpm | 12.9.1 | `packageManager` in frontend/package.json, frontend/pnpm-lock.yaml | +| React, React DOM | 19.3.0 | frontend/package.json, frontend/pnpm-lock.yaml | +| React Router (`react-router-dom`) | 7.18.4 | frontend/package.json, frontend/pnpm-lock.yaml | +| TanStack Query (`@tanstack/react-query`) | 5.104.1 | frontend/package.json, frontend/pnpm-lock.yaml | +| Zod | 4.6.5 | frontend/package.json, frontend/pnpm-lock.yaml | +| Vite | 8.3.2 | frontend/package.json, frontend/pnpm-lock.yaml | +| TypeScript | 7.0.2 (`@typescript/native`, `tsc`); 6.0.2 API (`typescript` alias of `@typescript/typescript6`) for ESLint | frontend/package.json, frontend/pnpm-lock.yaml | +| Vitest | 5.0.3 | frontend/package.json, frontend/pnpm-lock.yaml | +| Orval | 8.40.0 | frontend/package.json, frontend/pnpm-lock.yaml | +| Python | 3.14.8 (`requires-python >=3.14,<3.15`) | ml/.python-version, ml/pyproject.toml | +| uv | 0.12.22 | `[tool.uv] required-version` in ml/pyproject.toml; `setup-uv` in .github/workflows/ci.yml | +| FastAPI | 0.142.2 | ml/pyproject.toml, ml/uv.lock | +| Pydantic | 2.13.5 | ml/pyproject.toml, ml/uv.lock | +| uvicorn | 0.54.0 | ml/pyproject.toml, ml/uv.lock | +| ogen | v1.24.0 | backend/go.mod (`require` and `tool`) | +| sqlc | v1.31.1 | backend/go.mod (`tool`) | +| wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` and `tool`) | +| mockery | v3.8.0 | backend/go.mod (`tool`) | +| golangci-lint | v2.14.0 | backend/go.mod (`tool`) | +| goose | v3.28.0 | backend/go.mod (`tool`) | +| chi | v5.3.2 | backend/go.mod | +| pgx | v5.11.0 | backend/go.mod | +| testcontainers-go | v0.44.0, including modules/postgres | backend/go.mod | + +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, and a 404 for an unknown API route; it does not start ML. +- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap. +- 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 a home page, a generated API client, and MSW handlers. +- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). +- 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, consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, mail delivery, Kafka/outbox, notifications, support, and an end-to-end business suite. backend/db/migrations/ has no business schema, product usecase and adapter directories 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 The frontend uses TypeScript 7.0.2 (`tsc`) for type checking. The `@typescript/native` npm alias points to that compiler, while `typescript` points to the compatible `@typescript/typescript6` API for ESLint. This follows [Microsoft's side-by-side setup](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): current typescript-eslint does not support the TS7 API yet. Type checking covers source files, Vite configuration, and `codegen/orval.config.ts`. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 5f9e55c..aed6bbb 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -17,7 +17,7 @@ Для текущего `postgres:alpine` volume монтируется в `/var/lib/postgresql`; образ размещает данные в подкаталоге своей major-версии. При переходе тега на новую major-версию существующую базу нужно мигрировать через `pg_upgrade` или backup/restore. Обновление образа само по себе не преобразует данные. -Откройте http://127.0.0.1:8080. Порт привязан к loopback. Nginx отвечает на /healthz, перенаправляет /api/ в Go и использует SPA fallback для остальных путей. Go health endpoint находится на /api/v1/healthz; внутренний Go /readyz проверяет PostgreSQL через SELECT 1, Redis через PING и bucket SeaweedFS через HeadBucket; недоступность любого из них дает 503. Служебный /metrics слушает на внутреннем порту backend 9090. +Откройте http://127.0.0.1:8080. Порт привязан к loopback. Nginx отвечает на /healthz, перенаправляет /api/ в Go и использует SPA fallback для остальных путей. Публичный health-маршрут API - /api/v1/healthz через Nginx /api/. На внутреннем порту 8080 Go также обслуживает /healthz для проверки процесса и /readyz, который проверяет PostgreSQL через SELECT 1, Redis через PING и bucket SeaweedFS через HeadBucket; недоступность любого из них дает 503. Служебный /metrics слушает на внутреннем порту backend 9090. Этот Nginx конфиг не настраивает production TLS. Текущий bind не открывает приложение напрямую во внешнюю сеть. Для удаленного доступа требуется отдельно выбранный TLS reverse proxy, firewall и конфигурация целевого окружения. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index fc210be..ac158aa 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -13,6 +13,49 @@ Frontend зависимости выбираются из актуальных stable releases; сохраняйте pnpm-lock.yaml для повторяемой установки. ML зависимости фиксируются в uv.lock, Go dependencies - в backend/go.mod. При обновлении меняйте соответствующий lock/config и запускайте checks области. Образы используют заданные moving `latest` или `alpine` tags; сверяйте ссылки в Compose/Dockerfiles и не считайте их стабильными номерами версии. +## Состояние каркаса + +В репозитории есть проверяемый технический каркас, а не готовый продукт. Значения ниже взяты из указанных файлов; при обновлении зависимости меняйте ее источник и lockfile, затем обновляйте эту таблицу на обоих языках. + +| Компонент | Закрепленная версия | Источник | +| --- | --- | --- | +| Go | 1.26.8 (директива `go`; отдельной строки `toolchain` нет) | backend/go.mod; build image `golang:1.26.8-alpine` в backend/Dockerfile | +| Node.js | 26.10.0 | frontend/.node-version | +| pnpm | 12.9.1 | `packageManager` в frontend/package.json, frontend/pnpm-lock.yaml | +| React, React DOM | 19.3.0 | frontend/package.json, frontend/pnpm-lock.yaml | +| React Router (`react-router-dom`) | 7.18.4 | frontend/package.json, frontend/pnpm-lock.yaml | +| TanStack Query (`@tanstack/react-query`) | 5.104.1 | frontend/package.json, frontend/pnpm-lock.yaml | +| Zod | 4.6.5 | frontend/package.json, frontend/pnpm-lock.yaml | +| Vite | 8.3.2 | frontend/package.json, frontend/pnpm-lock.yaml | +| TypeScript | 7.0.2 (`@typescript/native`, `tsc`); API 6.0.2 (`typescript` как alias `@typescript/typescript6`) для ESLint | frontend/package.json, frontend/pnpm-lock.yaml | +| Vitest | 5.0.3 | frontend/package.json, frontend/pnpm-lock.yaml | +| Orval | 8.40.0 | frontend/package.json, frontend/pnpm-lock.yaml | +| Python | 3.14.8 (`requires-python >=3.14,<3.15`) | ml/.python-version, ml/pyproject.toml | +| uv | 0.12.22 | `[tool.uv] required-version` в ml/pyproject.toml; `setup-uv` в .github/workflows/ci.yml | +| FastAPI | 0.142.2 | ml/pyproject.toml, ml/uv.lock | +| Pydantic | 2.13.5 | ml/pyproject.toml, ml/uv.lock | +| uvicorn | 0.54.0 | ml/pyproject.toml, ml/uv.lock | +| ogen | v1.24.0 | backend/go.mod (`require` и `tool`) | +| sqlc | v1.31.1 | backend/go.mod (`tool`) | +| wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` и `tool`) | +| mockery | v3.8.0 | backend/go.mod (`tool`) | +| golangci-lint | v2.14.0 | backend/go.mod (`tool`) | +| goose | v3.28.0 | backend/go.mod (`tool`) | +| chi | v5.3.2 | backend/go.mod | +| pgx | v5.11.0 | backend/go.mod | +| testcontainers-go | v0.44.0, включая modules/postgres | backend/go.mod | + +Что есть сейчас: + +- Маршруты 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 маршрута; ML он не запускает. +- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. +- 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, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). +- 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-приложение пока не отправляет телеметрию. + +Еще не реализованы: регистрация и вход, согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Kafka/outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). + ## Установка и цикл работы Frontend проверяется компилятором TypeScript 7.0.2 (`tsc`). Пакет `@typescript/native` ссылается на него через npm alias, а `typescript` ссылается на совместимый API `@typescript/typescript6` для ESLint. Это [рекомендованная Microsoft схема совместного использования](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): текущий typescript-eslint еще не работает с API TS7. В проверку типов входят исходники, Vite config и `codegen/orval.config.ts`. diff --git a/scripts/docs-check.py b/scripts/docs-check.py index ac384b2..afa7c40 100644 --- a/scripts/docs-check.py +++ b/scripts/docs-check.py @@ -1,11 +1,16 @@ #!/usr/bin/env python3 -"""Check project-owned Markdown links, language docs, routes, and imports.""" +"""Check project-owned Markdown links, language docs, routes, and imports. + +Inside a git work tree, Markdown files that git ignores (for example through +.gitignore or .git/info/exclude) are local material and are not checked. +""" from __future__ import annotations import argparse import os import re +import subprocess import sys from pathlib import Path from urllib.parse import unquote, urlsplit @@ -45,7 +50,52 @@ HEADING = re.compile(r"^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$") HTML_ID = re.compile(r"\bid\s*=\s*['\"]([^'\"]+)['\"]", re.IGNORECASE) +class GitIgnoreError(RuntimeError): + """Raised when git reports a work tree but cannot evaluate ignore rules.""" + + +def inside_git_work_tree(root: Path) -> bool: + """Return True only when git is available and root belongs to a work tree.""" + try: + result = subprocess.run( + ["git", "-C", str(root), "rev-parse", "--is-inside-work-tree"], + capture_output=True, + check=False, + ) + except OSError: + return False + return result.returncode == 0 and result.stdout.strip() == b"true" + + +def git_ignored(root: Path, paths: list[Path]) -> set[Path]: + """Return the paths that git ignores, using one check-ignore call. + + Tracked files are never reported because check-ignore runs without + --no-index, so only local files that git would not track are skipped. + """ + if not paths or not inside_git_work_tree(root): + return set() + by_name = {path.relative_to(root).as_posix(): path for path in paths} + payload = b"".join(os.fsencode(name) + b"\0" for name in by_name) + try: + result = subprocess.run( + ["git", "check-ignore", "--stdin", "-z"], + cwd=root, + input=payload, + capture_output=True, + check=False, + ) + except OSError as error: + raise GitIgnoreError(f"git check-ignore could not run: {error}") from error + # Exit status 1 means that no path is ignored; anything else is a failure. + if result.returncode not in (0, 1): + message = result.stderr.decode("utf-8", errors="replace").strip() + raise GitIgnoreError(f"git check-ignore failed with status {result.returncode}: {message}") + return {by_name[os.fsdecode(name)] for name in result.stdout.split(b"\0") if name} + + def markdown_files(root: Path) -> list[Path]: + root = root.resolve() found: list[Path] = [] for current, directories, filenames in os.walk(root): directories[:] = sorted( @@ -57,7 +107,8 @@ def markdown_files(root: Path) -> list[Path]: path = Path(current) / filename if path.suffix.lower() == ".md" and not path.is_symlink(): found.append(path.resolve()) - return sorted(found) + ignored = git_ignored(root, found) + return sorted(path for path in found if path not in ignored) def visible_lines(markdown: str) -> list[tuple[int, str]]: @@ -294,7 +345,10 @@ def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) args = parser.parse_args() - errors = validate_repository(args.root) + try: + errors = validate_repository(args.root) + except GitIgnoreError as error: + errors = [str(error)] if errors: for error in errors: print(f"ERROR: {error}", file=sys.stderr) diff --git a/scripts/test_docs_check.py b/scripts/test_docs_check.py index aa8ecf4..e94c3f7 100644 --- a/scripts/test_docs_check.py +++ b/scripts/test_docs_check.py @@ -1,9 +1,13 @@ from __future__ import annotations import importlib.util +import os +import shutil +import subprocess import tempfile import unittest from pathlib import Path +from unittest import mock MODULE_PATH = Path(__file__).with_name("docs-check.py") @@ -13,7 +17,9 @@ DOCS_CHECK = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(DOCS_CHECK) -class DocsCheckTests(unittest.TestCase): +class RepositoryTestCase(unittest.TestCase): + """Create a minimal valid repository layout in a temporary directory.""" + def setUp(self) -> None: self.temporary = tempfile.TemporaryDirectory() self.root = Path(self.temporary.name) @@ -40,6 +46,8 @@ class DocsCheckTests(unittest.TestCase): path.write_text(content, encoding="utf-8") return path + +class DocsCheckTests(RepositoryTestCase): def test_accepts_angle_bracket_path_with_spaces(self) -> None: self.write("README.md", "# Root\n\n[Guide]()\n") self.write("guides/guide with spaces.md", "# Guide\n") @@ -119,5 +127,62 @@ class DocsCheckTests(unittest.TestCase): self.assertTrue(any("instruction import cycle" in error for error in errors), errors) +@unittest.skipUnless(shutil.which("git"), "git is required for ignore-rule tests") +class DocsCheckGitIgnoreTests(RepositoryTestCase): + LOCAL_README = "docs/other/notes/README.md" + + def setUp(self) -> None: + super().setUp() + # Isolate git from user and system configuration and from any parent repository. + environment = mock.patch.dict( + os.environ, + { + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CEILING_DIRECTORIES": str(self.root.resolve().parent), + }, + ) + environment.start() + self.addCleanup(environment.stop) + self.write(self.LOCAL_README, "[Missing](missing.md)\n") + + def git(self, *arguments: str) -> None: + subprocess.run(["git", *arguments], cwd=self.root, check=True, capture_output=True) + + def local_errors(self) -> list[str]: + errors = DOCS_CHECK.validate_repository(self.root) + return [error for error in errors if self.LOCAL_README in error] + + def test_skips_markdown_excluded_through_info_exclude(self) -> None: + self.git("init", "--quiet") + with (self.root / ".git" / "info" / "exclude").open("a", encoding="utf-8") as exclude: + exclude.write("/docs/other/\n") + self.assertEqual([], DOCS_CHECK.validate_repository(self.root)) + + def test_skips_markdown_ignored_through_gitignore(self) -> None: + self.git("init", "--quiet") + self.write(".gitignore", "/docs/other/\n") + self.assertEqual([], DOCS_CHECK.validate_repository(self.root)) + + def test_reports_untracked_markdown_that_is_not_ignored(self) -> None: + self.git("init", "--quiet") + errors = self.local_errors() + self.assertTrue(any("broken local link" in error for error in errors), errors) + self.assertTrue(any("README is below a top-level directory" in error for error in errors), errors) + + def test_reports_tracked_markdown_that_matches_ignore_rules(self) -> None: + self.git("init", "--quiet") + self.write(".gitignore", "/docs/other/\n") + self.git("add", "--force", self.LOCAL_README) + errors = self.local_errors() + self.assertTrue(any("broken local link" in error for error in errors), errors) + + def test_reports_markdown_outside_git_work_tree(self) -> None: + self.write(".gitignore", "/docs/other/\n") + errors = self.local_errors() + self.assertTrue(any("broken local link" in error for error in errors), errors) + self.assertTrue(any("README is below a top-level directory" in error for error in errors), errors) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/test_merge_schemas.py b/scripts/test_merge_schemas.py index e7c8890..7232439 100644 --- a/scripts/test_merge_schemas.py +++ b/scripts/test_merge_schemas.py @@ -23,7 +23,9 @@ class MergeSchemasTest(unittest.TestCase): def setUp(self) -> None: self.temporary = tempfile.TemporaryDirectory() self.addCleanup(self.temporary.cleanup) - self.contract_root = Path(self.temporary.name) / "api" + # merge_contract returns resolved paths; resolve the temporary root too because it + # may sit behind a symlink (for example /var -> /private/var on macOS). + self.contract_root = Path(self.temporary.name).resolve() / "api" (self.contract_root / "components" / "schemas").mkdir(parents=True) (self.contract_root / "routes").mkdir() From b2f6e87bfee64a8e56751fc520364f4da7bbe73e Mon Sep 17 00:00:00 2001 From: shira Date: Mon, 5 Oct 2026 21:20:46 +0300 Subject: [PATCH 002/143] feat(api): add composite ogen handler for incremental operations --- .../internal/adapter/primary/http/router.go | 7 ++- .../adapter/primary/http/router_test.go | 29 +++++++++-- .../adapter/primary/http/v1/handler.go | 44 ++++++++++++++++ .../adapter/primary/http/v1/handler_test.go | 51 +++++++++++++++++++ backend/internal/bootstrap/wire.go | 3 ++ backend/internal/bootstrap/wire_gen.go | 5 +- 6 files changed, 133 insertions(+), 6 deletions(-) create mode 100644 backend/internal/adapter/primary/http/v1/handler.go create mode 100644 backend/internal/adapter/primary/http/v1/handler_test.go diff --git a/backend/internal/adapter/primary/http/router.go b/backend/internal/adapter/primary/http/router.go index be382b5..2079aea 100644 --- a/backend/internal/adapter/primary/http/router.go +++ b/backend/internal/adapter/primary/http/router.go @@ -18,12 +18,17 @@ const ( readinessPath = "/readyz" ) +// NewRouter mounts the internal operational routes and the generated public API. +// The generated server keeps ogen's default error handler, which answers +// ht.ErrNotImplemented with HTTP 501; operations without a business +// implementation in apiHandler rely on that mapping. func NewRouter( health *v1.HealthHandler, + apiHandler apiadapter.Handler, collector httpmiddleware.RequestMetrics, logger *slog.Logger, ) (http.Handler, error) { - apiServer, err := apiadapter.NewServer(health) + apiServer, err := apiadapter.NewServer(apiHandler) if err != nil { return nil, fmt.Errorf("httpadapter.NewRouter - create API server: %w", err) } diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index 5d1bafc..7f11990 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "lincodex/backend/internal/adapter/primary/http/api" v1 "lincodex/backend/internal/adapter/primary/http/v1" metrics "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/usecase/health" @@ -70,11 +71,33 @@ func TestPublicHealthRouteUsesGeneratedOgenHandler(t *testing.T) { } } +// An operation without a business implementation must answer 501 through the +// router instead of a successful stub or a generic 500. GetHealthz served by +// api.UnimplementedHandler stands in for any such operation, so the check needs +// no extra contract operation. +func TestPublicUnimplementedOperationReturnsNotImplemented(t *testing.T) { + healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) + router := newTestRouterWithAPI(t, healthHandler, api.UnimplementedHandler{}) + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) + if response.Code != http.StatusNotImplemented { + t.Fatalf("status code = %d, want %d: %s", response.Code, http.StatusNotImplemented, response.Body.String()) + } +} + func newTestRouter(t *testing.T, checker readinessFunc) http.Handler { t.Helper() - readiness := health.NewReadiness(checker) - healthHandler := v1.NewHealthHandler(readiness, time.Second) - router, err := NewRouter(healthHandler, metrics.New(), slog.New(slog.DiscardHandler)) + healthHandler := newTestHealthHandler(checker) + return newTestRouterWithAPI(t, healthHandler, v1.NewHandler(healthHandler)) +} + +func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler { + return v1.NewHealthHandler(health.NewReadiness(checker), time.Second) +} + +func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler) http.Handler { + t.Helper() + router, err := NewRouter(healthHandler, apiHandler, metrics.New(), slog.New(slog.DiscardHandler)) if err != nil { t.Fatalf("NewRouter() error = %v", err) } diff --git a/backend/internal/adapter/primary/http/v1/handler.go b/backend/internal/adapter/primary/http/v1/handler.go new file mode 100644 index 0000000..d40933d --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/handler.go @@ -0,0 +1,44 @@ +package v1 + +import ( + "context" + + "lincodex/backend/internal/adapter/primary/http/api" +) + +// Handler is the composite implementation of the generated api.Handler. +// +// The embedded api.UnimplementedHandler keeps the backend compiling after the +// contract gains an operation that has no business implementation yet. Such an +// operation returns ht.ErrNotImplemented without side effects. The generated +// server passes that error to its configured ErrorHandler, and the default +// ogenerrors.DefaultErrorHandler maps it to HTTP 501. When the contract defines +// a default error response, the generated server still sends +// ht.ErrNotImplemented to ErrorHandler before calling NewError. The embedded +// NewError, however, returns a zero status code that the generated encoder +// sends as HTTP 200, so the composite must then define NewError explicitly. +// That NewError must answer *ogenerrors.SecurityError with 401 or 403, which +// the generated server passes to it directly, and answer every other error +// with 500 and a sanitized message, never err.Error() of an internal error. +// Errors of the generated status-code error type (*StatusCode) are +// encoded before NewError is called, so it does not need to handle them. +// +// Each implemented operation gets an explicit method here that delegates to +// the handler owning it. Each implemented operation also gets a router test +// through v1.NewHandler that asserts a non-501 response, because renaming an +// operationId would otherwise silently fall back to the embedded 501 method. +type Handler struct { + api.UnimplementedHandler + + health *HealthHandler +} + +var _ api.Handler = (*Handler)(nil) + +func NewHandler(health *HealthHandler) *Handler { + return &Handler{health: health} +} + +func (handler *Handler) GetHealthz(ctx context.Context) (*api.HealthResponse, error) { + return handler.health.GetHealthz(ctx) +} diff --git a/backend/internal/adapter/primary/http/v1/handler_test.go b/backend/internal/adapter/primary/http/v1/handler_test.go new file mode 100644 index 0000000..58ce015 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/handler_test.go @@ -0,0 +1,51 @@ +package v1 + +import ( + "context" + "errors" + "net/http" + "reflect" + "testing" +) + +// Once the contract defines a default error response, ogen adds NewError to +// api.Handler and api.UnimplementedHandler supplies one that returns a zero +// status code, which the generated encoder sends as HTTP 200. A handler error +// would then look like a success, so the composite must define its own NewError. +func TestHandlerNewErrorDoesNotReportSuccess(t *testing.T) { + newError := reflect.ValueOf(NewHandler(nil)).MethodByName("NewError") + if !newError.IsValid() { + t.Skip("the contract has no default error response, so the generated server has no NewError") + } + contextType := reflect.TypeFor[context.Context]() + errorType := reflect.TypeFor[error]() + signature := newError.Type() + if signature.NumIn() != 2 || signature.In(0) != contextType || signature.In(1) != errorType || signature.NumOut() != 1 { + t.Fatalf("NewError has signature %s, want func(context.Context, error) ", signature) + } + + results := newError.Call([]reflect.Value{ + reflect.ValueOf(context.Background()), + reflect.ValueOf(errors.New("handler failure")), + }) + if len(results) != 1 { + t.Fatalf("NewError() returned %d values, want 1", len(results)) + } + response := results[0] + if response.Kind() == reflect.Pointer { + if response.IsNil() { + t.Fatal("NewError() returned nil") + } + response = response.Elem() + } + if response.Kind() != reflect.Struct { + t.Fatalf("NewError() result kind = %s, want struct", response.Kind()) + } + statusCode := response.FieldByName("StatusCode") + if !statusCode.IsValid() || !statusCode.CanInt() { + t.Fatalf("NewError() result %s has no integer StatusCode field", response.Type()) + } + if code := statusCode.Int(); code < http.StatusBadRequest { + t.Fatalf("v1.Handler must define NewError with an error status: NewError yields status %d; the promoted api.UnimplementedHandler.NewError yields 0, which ogen encodes as HTTP 200", code) + } +} diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index 7ad5490..d698bfa 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -10,6 +10,7 @@ import ( "lincodex/backend/config" httpadapter "lincodex/backend/internal/adapter/primary/http" + apiadapter "lincodex/backend/internal/adapter/primary/http/api" httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware" v1 "lincodex/backend/internal/adapter/primary/http/v1" "lincodex/backend/internal/adapter/secondary/postgres" @@ -28,9 +29,11 @@ func initialize(ctx context.Context, config config.Config, logger *slog.Logger) seaweedfs.NewStorage, wire.Bind(new(inbound.Readiness), new(*health.Readiness)), wire.Bind(new(httpmiddleware.RequestMetrics), new(*metrics.Metrics)), + wire.Bind(new(apiadapter.Handler), new(*v1.Handler)), newReadiness, metrics.New, newHealthHandler, + v1.NewHandler, httpadapter.NewRouter, NewApplication, ), diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index 8506828..c95c8ba 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -40,15 +40,16 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger) } readiness := newReadiness(healthChecker, cache, storage) healthHandler := newHealthHandler(readiness, config2) + handler := v1.NewHandler(healthHandler) metrics := prometheus.New() - handler, err := httpadapter.NewRouter(healthHandler, metrics, logger) + httpHandler, err := httpadapter.NewRouter(healthHandler, handler, metrics, logger) if err != nil { cleanup3() cleanup2() cleanup() return nil, nil, err } - application := NewApplication(config2, handler, metrics, logger) + application := NewApplication(config2, httpHandler, metrics, logger) return application, func() { cleanup3() cleanup2() From 565ca94bbb05029d6821659cadb90de15343736f Mon Sep 17 00:00:00 2001 From: shira Date: Mon, 5 Oct 2026 22:09:36 +0300 Subject: [PATCH 003/143] feat(api): define public problem errors, pagination, and retry contract --- .github/workflows/ci.yml | 24 +- api/Makefile | 5 +- api/README.en.md | 89 +++ api/README.md | 89 +++ api/core/components/examples.yml | 140 +++++ api/core/components/headers.yml | 19 + api/core/components/parameters.yml | 58 ++ api/core/components/responses.yml | 159 ++++++ api/core/components/schemas.yml | 161 ++++++ .../components/schemas/common_schemas.yml | 34 ++ .../components/schemas/problem_schemas.yml | 146 +++++ api/core/openapi.bundle.yml | 505 +++++++++++++++++ api/core/openapi.yml | 57 ++ api/core/routes/healthz.yml | 7 + api/ml/components/responses.yml | 30 + api/ml/components/schemas.yml | 136 +++++ api/ml/components/schemas/problem_schemas.yml | 148 +++++ api/ml/openapi.bundle.yml | 155 ++++++ api/ml/openapi.yml | 4 + api/ml/routes/healthz.yml | 2 + api/ml/routes/readyz.yml | 2 + api/testdata/openapi-3.2.0.yml | 394 +++++++++++++ backend/Makefile | 2 +- .../adapter/primary/http/api/oas_cfg_gen.go | 6 + .../primary/http/api/oas_handlers_gen.go | 15 +- .../adapter/primary/http/api/oas_json_gen.go | 516 ++++++++++++++++++ .../http/api/oas_response_encoders_gen.go | 27 + .../primary/http/api/oas_schemas_gen.go | 457 ++++++++++++++++ .../primary/http/api/oas_server_gen.go | 4 + .../primary/http/api/oas_unimplemented_gen.go | 8 + .../primary/http/api/oas_validators_gen.go | 387 +++++++++++++ .../adapter/primary/http/problem/problem.go | 142 +++++ .../adapter/primary/http/problem/recover.go | 98 ++++ .../primary/http/problem/recover_test.go | 66 +++ .../adapter/primary/http/problem/responder.go | 240 ++++++++ .../primary/http/problem/responder_test.go | 261 +++++++++ .../internal/adapter/primary/http/router.go | 42 +- .../adapter/primary/http/router_test.go | 274 +++++++++- .../adapter/primary/http/v1/handler.go | 35 +- .../adapter/primary/http/v1/handler_test.go | 5 +- .../adapter/secondary/ml/api/oas_cfg_gen.go | 6 + .../adapter/secondary/ml/api/oas_json_gen.go | 516 ++++++++++++++++++ .../ml/api/oas_response_decoders_gen.go | 106 +++- .../secondary/ml/api/oas_schemas_gen.go | 457 ++++++++++++++++ .../secondary/ml/api/oas_validators_gen.go | 387 +++++++++++++ backend/internal/bootstrap/wire.go | 2 + backend/internal/bootstrap/wire_gen.go | 6 +- backend/testdata/ogen_compat_test.go | 279 +++++++++- docs/en/ARCHITECTURE.md | 3 +- docs/en/DEVELOPMENT.md | 2 + docs/ru/ARCHITECTURE.md | 3 +- docs/ru/DEVELOPMENT.md | 2 + frontend/.gitignore | 1 + frontend/.prettierignore | 1 + frontend/Makefile | 5 +- frontend/README.en.md | 2 +- frontend/README.md | 2 +- frontend/codegen/orval.config.ts | 94 +++- frontend/package.json | 3 +- frontend/scripts/check-orval-compat.mjs | 72 +++ frontend/src/shared/api/client.test.ts | 189 ++++++- frontend/src/shared/api/client.ts | 169 ++++-- .../src/shared/api/endpoints/health/health.ts | 16 +- frontend/src/shared/api/index.ts | 9 +- .../src/shared/api/schemas/health/index.ts | 4 + .../shared/api/schemas/health/problem.zod.ts | 54 ++ .../api/schemas/health/problemCode.zod.ts | 12 + .../schemas/health/problemFieldError.zod.ts | 28 + .../health/problemFieldLocation.zod.ts | 12 + frontend/src/shared/api/schemas/index.ts | 2 + .../src/shared/api/schemas/pageInfo.zod.ts | 20 + .../src/shared/api/schemas/timestamp.zod.ts | 12 + ml/Makefile | 16 +- ml/README.en.md | 1 + ml/README.md | 1 + ml/codegen/pyproject.toml | 2 + ml/scripts/check_fixture_models.py | 86 +++ ml/src/lincodex_ml/api/models.py | 143 ++++- ml/src/lincodex_ml/api/problems.py | 281 ++++++++++ ml/src/lincodex_ml/infra/logging.py | 36 +- ml/src/lincodex_ml/main.py | 2 + ml/tests/test_contract.py | 35 +- ml/tests/test_problems.py | 215 ++++++++ scripts/README.en.md | 2 +- scripts/README.md | 2 +- scripts/test_contract_copies.py | 107 ++++ 86 files changed, 8200 insertions(+), 154 deletions(-) create mode 100644 api/core/components/examples.yml create mode 100644 api/core/components/headers.yml create mode 100644 api/core/components/parameters.yml create mode 100644 api/core/components/responses.yml create mode 100644 api/core/components/schemas/common_schemas.yml create mode 100644 api/core/components/schemas/problem_schemas.yml create mode 100644 api/ml/components/responses.yml create mode 100644 api/ml/components/schemas/problem_schemas.yml create mode 100644 backend/internal/adapter/primary/http/problem/problem.go create mode 100644 backend/internal/adapter/primary/http/problem/recover.go create mode 100644 backend/internal/adapter/primary/http/problem/recover_test.go create mode 100644 backend/internal/adapter/primary/http/problem/responder.go create mode 100644 backend/internal/adapter/primary/http/problem/responder_test.go create mode 100644 frontend/scripts/check-orval-compat.mjs create mode 100644 frontend/src/shared/api/schemas/health/problem.zod.ts create mode 100644 frontend/src/shared/api/schemas/health/problemCode.zod.ts create mode 100644 frontend/src/shared/api/schemas/health/problemFieldError.zod.ts create mode 100644 frontend/src/shared/api/schemas/health/problemFieldLocation.zod.ts create mode 100644 frontend/src/shared/api/schemas/pageInfo.zod.ts create mode 100644 frontend/src/shared/api/schemas/timestamp.zod.ts create mode 100644 ml/scripts/check_fixture_models.py create mode 100644 ml/src/lincodex_ml/api/problems.py create mode 100644 ml/tests/test_problems.py create mode 100644 scripts/test_contract_copies.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc75846..b439b83 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: api: name: API contracts runs-on: ubuntu-24.04 - timeout-minutes: 20 + timeout-minutes: 30 steps: - name: Check out source uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 @@ -46,8 +46,30 @@ jobs: python-version-file: ml/.python-version cache: pip cache-dependency-path: scripts/requirements-codegen.txt + # make -C api verify runs check-toolchain, which generates the OpenAPI 3.2 + # fixture with ogen, Orval, and datamodel-code-generator, so the job also + # needs the frontend and ML toolchains. + - name: Install declared pnpm + run: npm install --global "$(node -p "require('./frontend/package.json').packageManager")" + - name: Cache pnpm store + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ~/.local/share/pnpm/store + key: ${{ runner.os }}-pnpm-${{ hashFiles('frontend/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm- + - name: Set up uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + version: 0.12.22 + enable-cache: true + cache-dependency-glob: ml/uv.lock - name: Install API tooling run: make -C api install + - name: Install frontend dependencies + run: make -C frontend install + - name: Install ML dependencies + run: make -C ml install - name: Check API formatting and compatibility run: make -C api fmt-check verify - name: Check compatibility with the pull request base diff --git a/api/Makefile b/api/Makefile index 896160a..8f2be02 100644 --- a/api/Makefile +++ b/api/Makefile @@ -30,15 +30,18 @@ lint: bundle ## Lint both bundled contracts .PHONY: check check: lint ## Build and lint both contract bundles PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_merge_schemas.py' + PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_contract_copies.py' .PHONY: check-compat check-compat: bundle ## Compare the public contract with API_BASE_REF API_BASE_REF="$(API_BASE_REF)" REDOCLY="$(REDOCLY)" CODEGEN_PYTHON="$(CODEGEN_PYTHON)" bash "$(ROOT_DIR)/scripts/check-api-compat.sh" .PHONY: check-toolchain -check-toolchain: ## Check OpenAPI 3.2.0 support and generated validation behavior +check-toolchain: ## Check OpenAPI 3.2.0 support with ogen, Orval, and Pydantic on the compatibility fixture "$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/testdata/openapi-3.2.0.yml" $(MAKE) -C "$(ROOT_DIR)/backend" check-ogen-compat + $(MAKE) -C "$(ROOT_DIR)/frontend" check-orval-compat + $(MAKE) -C "$(ROOT_DIR)/ml" check-pydantic-compat .PHONY: fmt fmt: ## Format handwritten OpenAPI YAML files diff --git a/api/README.en.md b/api/README.en.md index a738156..97f60cf 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -12,4 +12,93 @@ Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml` From the repository root, `make -C api check` checks contracts and `make generate` updates all generated code. +## Contract conventions + +`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for future business operations; no public operation uses them yet. + +### Errors + +Every error is an RFC 9457 problem with the `application/problem+json` media type and the `Problem` schema. Required fields are `type` (`urn:lincodex:problem:`), `title`, `status`, and `code`; optional ones are `detail`, `instance`, `trace_id` (equal to the `X-Request-ID` response header), and `errors`. Clients branch on `code`. Titles and details are fixed per code and never contain internal error text, stack traces, credentials, contact data, or submitted values. + +| Code | Status | Meaning | +| --- | --- | --- | +| `validation_failed` | 400 | Parameters or body do not match the contract, or the body violates a domain rule; `errors` lists the fields | +| `unauthenticated` | 401 | No valid session | +| `forbidden` | 403 | The caller may not perform the operation | +| `not_found` | 404 | Unknown route, or an object that does not exist or is not visible | +| `method_not_allowed` | 405 | Unsupported method; see `Allow` | +| `idempotency_in_progress` | 409 | A request with the same Idempotency-Key is still running | +| `state_conflict` | 409 | The operation is not allowed in the current state of the resource | +| `version_conflict` | 412 | If-Match does not match the current version | +| `payload_too_large` | 413 | The body exceeds the operation limit | +| `unsupported_media_type` | 415 | The request Content-Type is not accepted | +| `idempotency_key_reused` | 422 | The Idempotency-Key was used with a different request | +| `precondition_required` | 428 | The operation requires If-Match | +| `rate_limited` | 429 | Too many requests; see `Retry-After` | +| `internal` | 500 | Unexpected server error | +| `not_implemented` | 501 | The operation is in the contract but not implemented | + +Request validation uses 400 rather than 422. The generated ogen server reports malformed and schema-invalid parameters and bodies through the same decoding errors, and for parameters it does not separate syntax from schema violations; one status keeps client handling uniform. 422 then stays free for Idempotency-Key reuse, as the IETF Idempotency-Key header draft recommends. Domain rules on the body, such as `salary_from <= salary_to`, also answer 400 `validation_failed` with body pointers to the fields involved. Each `errors` item has `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` in the body, an empty string for the whole body, `/limit` for a parameter), `code` (`required` or `invalid`; clients tolerate new values), and a fixed `message`. When the decoder does not record the path of a nested body field, the pointer is the whole body. A body cut by an `http.MaxBytesReader` limit answers 413 `payload_too_large`. + +`state_conflict` covers business state conflicts, such as accepting an invitation that was already withdrawn. `idempotency_in_progress` is reserved for concurrent retries; the reusable responses are `StateConflict` and `IdempotencyInProgress`. + +Every operation declares `default: $ref: ../components/responses.yml#/Problem`; ogen then generates a single error type. An operation adds a specific response (for example `PreconditionFailed`) when clients need it in the generated types. In the Go API, unknown paths under `/api`, including paths outside `/api/v1`, answer 404 `not_found`, and a panic in an operation answers 500 `internal`; only the panic type and stack are logged. + +### Retries and Idempotency-Key + +A mutating command declares the `IdempotencyKey` parameter. The client generates a key (a UUID v4 is recommended) and sends it in the `Idempotency-Key` header without quotes: 1-255 characters `A-Z a-z 0-9 . _ : -`. The server scopes the key by caller and operation and fingerprints the request by method, path, and body. + +Stored for 24 hours and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 `not_found` or 409 `state_conflict`. A replay does not repeat the side effect. + +Not stored, so a retry with the same key is evaluated again: 400 `validation_failed`, 413, and 415 for the request itself; 401 and 403; 409 `idempotency_in_progress`; 412 `version_conflict` and 428 `precondition_required` (nothing changed; read the resource again and retry); 422 `idempotency_key_reused`; 429; and every 5xx. + +The server checks in this order: + +1. Authentication (401), request validation (400, 413, 415), and authorization (403). Nothing is recorded for the key. +2. A stored or running request with the same key and a different fingerprint: 422 `idempotency_key_reused`. This check comes before the in-progress check. +3. A running request with the same key and fingerprint: 409 `idempotency_in_progress`; retry later. +4. A stored outcome with the same key and fingerprint: the outcome is replayed. +5. If-Match (428, 412), then the command itself; a storable outcome is recorded. + +Because the replay check comes before If-Match, a retry of a completed change replays its outcome instead of failing on the version that the change itself advanced. A missing or malformed key returns 400 `validation_failed` with the pointer `/Idempotency-Key`. After 24 hours the key may be accepted as new. + +### Versions: ETag and If-Match + +A response with a versioned resource returns a strong `ETag`, for example `"v7"`. An operation that changes such a resource says in its description that it requires `If-Match` with that value. A missing value returns 428 `precondition_required`; a value that does not equal the current ETag returns 412 `version_conflict` and changes nothing. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. Weak tags, lists, and `*` fail validation with 400. + +### Pagination + +Lists use cursor pagination: `limit` from 1 to 100 (20 by default) and an opaque `cursor` of up to 512 characters `A-Z a-z 0-9 _ -`. The response holds the items in a bounded array and `page` (`PageInfo`) with `has_more` and `next_cursor`, which is null on the last page. A malformed cursor returns 400 `validation_failed`. + +### Time and money + +Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with the `Z` suffix (RFC 3339). Servers always emit UTC. ogen generates `Timestamp` as a named Go type over `time.Time`; call `.UTC()` where a value is converted to it. Money is planned as an integer number of whole rubles with explicit fields for the base, such as the pay period and gross or net; the schema is added with the first business field that carries money. + +### ML service errors + +The ML service answers its errors with the same `Problem` schema. FastAPI request validation answers 400 `validation_failed`. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, and 501 to their codes, 422 to 400 `validation_failed`, any other 4xx to 400 `validation_failed`, and any other 5xx to 500 `internal`. An unhandled exception answers 500 `internal` inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback. + +### Generator checks + +`testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core. + +`make -C api check-toolchain` lints the fixture and runs the three generators on it; it needs the backend Go toolchain, pnpm, and uv, so pass the same `UV` override as for `make generate`. + +| Target | Generator | Exercised conventions | +| --- | --- | --- | +| `make -C backend check-ogen-compat` | ogen | All of them: Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch, ETag. Its tests check validation errors, the retry scenario, the preconditions, and the 413 body limit against the backend problem mapping | +| `make -C frontend check-orval-compat` | Orval | Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch. The output is type-checked with the frontend compiler settings | +| `make -C ml check-pydantic-compat` | datamodel-code-generator | Problem, PageInfo, Timestamp, PageLimit, PageCursor. The models pass `mypy --strict` and a validation script | + +Each target writes its output to a temporary directory and removes it. + +Known generator limitations: + +- Orval 8.40 writes no Zod schema for `components/responses` but imports a `Response` type for each reference. `frontend/codegen/orval.config.ts` therefore inlines response references before generation. +- Orval passes header parameters as a typed argument only with `headers: true`. With `exactOptionalPropertyTypes`, an optional header such as `If-Match` fits `RequestInit` only when Zod emits exact optional properties, so the configuration also sets `override.zod.exactOptional`. +- Orval generates no type for response headers, and `apiRequest` returns only the body, so a generated client cannot read `ETag` yet. The first operation with a versioned resource must expose it, for example through the response body or the mutator. +- datamodel-code-generator 0.83.0 generates models only for schemas and query and path parameters; header parameters and response headers (Idempotency-Key, If-Match, ETag) produce no Python model. +- Orval does not generate `additionalOperations` methods. +- ogen writes the header name in its canonical Go form (`Etag`); HTTP header names are case-insensitive. + See the [development guide](../docs/en/DEVELOPMENT.md). diff --git a/api/README.md b/api/README.md index d17bea6..bd56091 100644 --- a/api/README.md +++ b/api/README.md @@ -12,4 +12,93 @@ Из корня: `make -C api check` проверяет контракты, `make generate` обновляет весь сгенерированный код. +## Соглашения контракта + +`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение будущих бизнес-операций; ни одна публичная операция их пока не использует. + +### Ошибки + +Любая ошибка - problem по RFC 9457 с media type `application/problem+json` и схемой `Problem`. Обязательные поля: `type` (`urn:lincodex:problem:`), `title`, `status` и `code`; необязательные: `detail`, `instance`, `trace_id` (равен заголовку ответа `X-Request-ID`) и `errors`. Клиенты принимают решения по `code`. Заголовок и описание фиксированы для каждого кода и никогда не содержат текст внутренних ошибок, stack trace, учетные данные, контакты или отправленные значения. + +| Код | Статус | Значение | +| --- | --- | --- | +| `validation_failed` | 400 | Параметры или тело не соответствуют контракту или тело нарушает доменное правило; `errors` перечисляет поля | +| `unauthenticated` | 401 | Нет действующей сессии | +| `forbidden` | 403 | Вызывающему запрещена операция | +| `not_found` | 404 | Неизвестный маршрут или объект, который не существует или недоступен | +| `method_not_allowed` | 405 | Метод не поддерживается; см. `Allow` | +| `idempotency_in_progress` | 409 | Запрос с тем же Idempotency-Key еще выполняется | +| `state_conflict` | 409 | Операция недопустима в текущем состоянии ресурса | +| `version_conflict` | 412 | If-Match не совпадает с текущей версией | +| `payload_too_large` | 413 | Тело превышает лимит операции | +| `unsupported_media_type` | 415 | Content-Type запроса не принимается | +| `idempotency_key_reused` | 422 | Idempotency-Key уже использован с другим запросом | +| `precondition_required` | 428 | Операция требует If-Match | +| `rate_limited` | 429 | Слишком много запросов; см. `Retry-After` | +| `internal` | 500 | Непредвиденная ошибка сервера | +| `not_implemented` | 501 | Операция есть в контракте, но не реализована | + +Для валидации запроса выбран 400, а не 422. Сгенерированный ogen-сервер сообщает о синтаксически неверных и не прошедших проверку схемы параметрах и теле через одни и те же ошибки декодирования, а для параметров не отделяет синтаксис от нарушения схемы; единый статус упрощает обработку на клиенте. Поэтому 422 остается для повторного использования Idempotency-Key, как рекомендует черновик IETF о заголовке Idempotency-Key. Доменные правила тела, например `salary_from <= salary_to`, тоже отвечают 400 `validation_failed` с body pointer на участвующие поля. Каждый элемент `errors` содержит `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` в теле, пустая строка для всего тела, `/limit` для параметра), `code` (`required` или `invalid`; клиенты допускают новые значения) и фиксированный `message`. Если декодер не сохранил путь вложенного поля тела, pointer указывает на все тело. Тело, обрезанное лимитом `http.MaxBytesReader`, дает 413 `payload_too_large`. + +`state_conflict` обозначает конфликты бизнес-состояния, например принятие уже отозванного приглашения. `idempotency_in_progress` зарезервирован для параллельных повторов; переиспользуемые ответы - `StateConflict` и `IdempotencyInProgress`. + +Каждая операция объявляет `default: $ref: ../components/responses.yml#/Problem`; тогда ogen генерирует единый тип ошибки. Конкретный ответ (например, `PreconditionFailed`) операция добавляет, когда он нужен клиентам в сгенерированных типах. В Go API неизвестные пути под `/api`, включая пути вне `/api/v1`, отвечают 404 `not_found`, а panic в операции - 500 `internal`; в лог попадают только тип panic и stack. + +### Повторы и Idempotency-Key + +Изменяющая команда объявляет параметр `IdempotencyKey`. Клиент создает ключ (рекомендуется UUID v4) и передает его в заголовке `Idempotency-Key` без кавычек: 1-255 символов `A-Z a-z 0-9 . _ : -`. Сервер ограничивает ключ вызывающим и операцией и снимает отпечаток запроса по методу, пути и телу. + +Хранятся 24 часа и воспроизводятся с теми же статусом, заголовками и телом: итоговый 2xx-результат и итоговые детерминированные бизнес-результаты 4xx, например 404 `not_found` или 409 `state_conflict`. Воспроизведение не повторяет побочный эффект. + +Не хранятся, поэтому повтор с тем же ключом обрабатывается заново: 400 `validation_failed`, 413 и 415 для самого запроса; 401 и 403; 409 `idempotency_in_progress`; 412 `version_conflict` и 428 `precondition_required` (ничего не изменилось; прочитайте ресурс снова и повторите); 422 `idempotency_key_reused`; 429; любой 5xx. + +Порядок проверок на сервере: + +1. Аутентификация (401), валидация запроса (400, 413, 415) и авторизация (403). Для ключа ничего не записывается. +2. Сохраненный или выполняющийся запрос с тем же ключом и другим отпечатком: 422 `idempotency_key_reused`. Эта проверка идет раньше проверки выполнения. +3. Выполняющийся запрос с тем же ключом и отпечатком: 409 `idempotency_in_progress`; повторите позже. +4. Сохраненный результат с тем же ключом и отпечатком: результат воспроизводится. +5. If-Match (428, 412), затем сама команда; результат, который можно хранить, записывается. + +Поскольку проверка воспроизведения идет раньше If-Match, повтор завершенного изменения воспроизводит его результат, а не падает на версии, которую само изменение и увеличило. Отсутствующий или некорректный ключ дает 400 `validation_failed` с pointer `/Idempotency-Key`. Через 24 часа ключ может быть принят как новый. + +### Версии: ETag и If-Match + +Ответ с версионируемым ресурсом возвращает сильный `ETag`, например `"v7"`. Операция, изменяющая такой ресурс, указывает в описании, что требует `If-Match` с этим значением. Отсутствующее значение дает 428 `precondition_required`; значение, не равное текущему ETag, дает 412 `version_conflict` без изменений. В схеме параметр необязательный, чтобы отсутствие заголовка доходило до приложения, которое отвечает 428. Слабые теги, списки и `*` не проходят валидацию и дают 400. + +### Пагинация + +Списки используют cursor pagination: `limit` от 1 до 100 (по умолчанию 20) и непрозрачный `cursor` длиной до 512 символов `A-Z a-z 0-9 _ -`. Ответ содержит элементы в ограниченном массиве и `page` (`PageInfo`) с `has_more` и `next_cursor`, который равен null на последней странице. Некорректный cursor дает 400 `validation_failed`. + +### Время и деньги + +Метки времени используют схему `Timestamp`: `string`, `format: date-time`, UTC с суффиксом `Z` (RFC 3339). Серверы всегда отдают UTC. ogen генерирует `Timestamp` как именованный Go-тип поверх `time.Time`; при преобразовании к нему вызывайте `.UTC()`. Деньги запланированы как целое число полных рублей с явными полями базы, например периодом оплаты и gross или net; схема появится вместе с первым бизнес-полем с деньгами. + +### Ошибки ML-сервиса + +ML-сервис отвечает на ошибки той же схемой `Problem`. Валидация запроса FastAPI дает 400 `validation_failed`. HTTP-исключение внутри сервиса преобразуется по статусу: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429 и 501 - в свои коды, 422 - в 400 `validation_failed`, любой другой 4xx - в 400 `validation_failed`, любой другой 5xx - в 500 `internal`. Необработанное исключение дает 500 `internal` внутри приложения, поэтому Starlette не пробрасывает его в uvicorn; в лог попадает только тип. Сервис также направляет логгеры uvicorn через свой JSON-формат, который сохраняет только тип исключения записи, но не текст и не traceback. + +### Проверки генераторов + +`testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core. + +`make -C api check-toolchain` проверяет фикстуру линтером и запускает на ней три генератора; нужны Go toolchain backend, pnpm и uv, поэтому передавайте тот же `UV` override, что и для `make generate`. + +| Target | Генератор | Проверяемые соглашения | +| --- | --- | --- | +| `make -C backend check-ogen-compat` | ogen | Все: Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch, ETag. Тесты проверяют ошибки валидации, сценарий повтора, предусловия и лимит тела 413 вместе с backend-маппингом problem | +| `make -C frontend check-orval-compat` | Orval | Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch. Результат проходит проверку типов с настройками компилятора frontend | +| `make -C ml check-pydantic-compat` | datamodel-code-generator | Problem, PageInfo, Timestamp, PageLimit, PageCursor. Модели проходят `mypy --strict` и скрипт валидации | + +Каждый target пишет результат во временный каталог и удаляет его. + +Известные ограничения генераторов: + +- Orval 8.40 не создает Zod-схемы для `components/responses`, но импортирует тип `Response` для каждой ссылки. Поэтому `frontend/codegen/orval.config.ts` встраивает ссылки на ответы перед генерацией. +- Orval передает header-параметры типизированным аргументом только с `headers: true`. С `exactOptionalPropertyTypes` необязательный заголовок, например `If-Match`, совместим с `RequestInit` только при точных необязательных свойствах Zod, поэтому конфигурация также задает `override.zod.exactOptional`. +- Orval не генерирует типы заголовков ответа, а `apiRequest` возвращает только тело, поэтому сгенерированный клиент пока не может прочитать `ETag`. Первая операция с версионируемым ресурсом должна открыть его, например через тело ответа или mutator. +- datamodel-code-generator 0.83.0 создает модели только для схем и query- и path-параметров; header-параметры и заголовки ответа (Idempotency-Key, If-Match, ETag) не дают Python-моделей. +- Orval не генерирует методы для `additionalOperations`. +- ogen записывает имя заголовка в канонической Go-форме (`Etag`); имена HTTP-заголовков не зависят от регистра. + Подробнее: [разработка](../docs/ru/DEVELOPMENT.md). diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml new file mode 100644 index 0000000..a49ed3f --- /dev/null +++ b/api/core/components/examples.yml @@ -0,0 +1,140 @@ +ValidationFailed: + summary: Request parameters do not match the contract + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10 + errors: + - in: query + pointer: /limit + code: invalid + message: The value does not match the contract. + - in: header + pointer: /Idempotency-Key + code: required + message: The value is required. +Unauthenticated: + summary: No valid session + value: + type: urn:lincodex:problem:unauthenticated + title: Authentication required + status: 401 + code: unauthenticated + detail: Sign in and repeat the request. + trace_id: 4f2d1c3b-6a5e-4d7f-8b9a-0c1d2e3f4a5b +Forbidden: + summary: The caller may not access the object + value: + type: urn:lincodex:problem:forbidden + title: Access denied + status: 403 + code: forbidden + detail: You do not have permission to perform this operation. + trace_id: 7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d +NotFound: + summary: Unknown route or invisible object + value: + type: urn:lincodex:problem:not_found + title: Resource not found + status: 404 + code: not_found + detail: The requested resource does not exist. + trace_id: 1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f +IdempotencyInProgress: + summary: The first request with this key is still running + value: + type: urn:lincodex:problem:idempotency_in_progress + title: Request with this idempotency key is in progress + status: 409 + code: idempotency_in_progress + detail: Retry after the original request completes. + trace_id: 2d3e4f5a-6b7c-4d8e-9f0a-1b2c3d4e5f6a +StateConflict: + summary: The resource state does not allow the operation + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b +DomainValidationFailed: + summary: The body violates a domain rule + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 2f3a4b5c-6d7e-4f8a-9b0c-1d2e3f4a5b6c + errors: + - in: body + pointer: /salary_from + code: invalid + message: The value does not match the contract. +VersionConflict: + summary: If-Match does not match the current version + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 3e4f5a6b-7c8d-4e9f-8a0b-2c3d4e5f6a7b +PayloadTooLarge: + summary: The request body exceeds the limit + value: + type: urn:lincodex:problem:payload_too_large + title: Request body too large + status: 413 + code: payload_too_large + detail: Reduce the request body size and retry. + trace_id: 8b9c0d1e-2f3a-4b4c-9d5e-6f7a8b9c0d1e +IdempotencyKeyReused: + summary: The same Idempotency-Key was sent with a different body + value: + type: urn:lincodex:problem:idempotency_key_reused + title: Idempotency key reused with a different request + status: 422 + code: idempotency_key_reused + detail: Use a new Idempotency-Key for a different request. + trace_id: 4f5a6b7c-8d9e-4f0a-9b1c-3d4e5f6a7b8c +PreconditionRequired: + summary: The operation requires If-Match + value: + type: urn:lincodex:problem:precondition_required + title: Precondition required + status: 428 + code: precondition_required + detail: Send If-Match with the ETag of the version you read. + trace_id: 5a6b7c8d-9e0f-4a1b-8c2d-4e5f6a7b8c9d +RateLimited: + summary: Too many requests + value: + type: urn:lincodex:problem:rate_limited + title: Too many requests + status: 429 + code: rate_limited + detail: Wait for the Retry-After interval and retry. + trace_id: 6b7c8d9e-0f1a-4b2c-9d3e-5f6a7b8c9d0e +Internal: + summary: Unexpected server error + value: + type: urn:lincodex:problem:internal + title: Internal server error + status: 500 + code: internal + detail: The server could not complete the request. + trace_id: 9c0d1e2f-3a4b-4c5d-8e6f-7a8b9c0d1e2f +NotImplemented: + summary: Operation declared in the contract without an implementation + value: + type: urn:lincodex:problem:not_implemented + title: Operation not implemented + status: 501 + code: not_implemented + detail: This operation is not available yet. + trace_id: 0d1e2f3a-4b5c-4d6e-9f7a-8b9c0d1e2f3a diff --git a/api/core/components/headers.yml b/api/core/components/headers.yml new file mode 100644 index 0000000..6f30714 --- /dev/null +++ b/api/core/components/headers.yml @@ -0,0 +1,19 @@ +ETag: + description: >- + Strong entity tag of the returned resource version. Send it back in + If-Match to change this version. + required: true + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: '^"[A-Za-z0-9._~-]{1,128}"$' + example: '"v7"' +RetryAfter: + description: Number of seconds to wait before retrying the request. + schema: + type: integer + format: int32 + minimum: 0 + maximum: 86400 + example: 30 diff --git a/api/core/components/parameters.yml b/api/core/components/parameters.yml new file mode 100644 index 0000000..5d5a111 --- /dev/null +++ b/api/core/components/parameters.yml @@ -0,0 +1,58 @@ +IdempotencyKey: + name: Idempotency-Key + in: header + required: true + description: |- + Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value is sent without quotes. The server scopes the key by caller and operation and fingerprints the request by method, path, and body. + + Stored for 24 hours after the first request and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 not_found or 409 state_conflict. A replay does not repeat the side effect. + + Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 precondition_required (nothing changed; read the resource again and retry), 422 idempotency_key_reused, 429, and every 5xx. + + Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused before any other key check; a running request with the same fingerprint returns 409 idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that does the server check If-Match, so a retry of a completed change replays its outcome instead of failing on the version it has just changed. After 24 hours the key may be accepted as new. + schema: + type: string + minLength: 1 + maxLength: 255 + pattern: "^[A-Za-z0-9._:-]+$" + example: 5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11 +IfMatch: + name: If-Match + in: header + required: false + description: |- + Strong entity tag of the resource version the client last read, copied from the ETag response header. An operation that changes a versioned resource says in its own description that it requires If-Match. + + On such an operation, a missing If-Match returns 428 precondition_required. An If-Match that does not equal the current ETag returns 412 version_conflict and changes nothing; read the resource again before retrying. Only one strong entity tag is accepted; weak tags, lists, and `*` fail validation with 400. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: '^"[A-Za-z0-9._~-]{1,128}"$' + example: '"v7"' +PageLimit: + name: limit + in: query + required: false + description: >- + Maximum number of items in the page. The server may return fewer items + even when more remain; use `page.has_more` to detect the end. + schema: + type: integer + format: int32 + minimum: 1 + maximum: 100 + default: 20 +PageCursor: + name: cursor + in: query + required: false + description: >- + Opaque `page.next_cursor` value from the previous page of the same listing. + Omit it to read the first page. A malformed or foreign cursor returns 400 + with code validation_failed. + schema: + type: string + minLength: 1 + maxLength: 512 + pattern: "^[A-Za-z0-9_-]+$" diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml new file mode 100644 index 0000000..96032ea --- /dev/null +++ b/api/core/components/responses.yml @@ -0,0 +1,159 @@ +ValidationFailed: + description: >- + Parameters, headers, or the body do not match the contract, or the body + violates a domain rule such as salary_from <= salary_to. The body has code + validation_failed and lists the failing fields in `errors` with body or + parameter pointers. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + validation_failed: + $ref: ./examples.yml#/ValidationFailed + domain_rule: + $ref: ./examples.yml#/DomainValidationFailed +Unauthenticated: + description: No valid session or credentials; code unauthenticated. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + unauthenticated: + $ref: ./examples.yml#/Unauthenticated +Forbidden: + description: >- + The caller is authenticated but may not perform the operation; code + forbidden. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + forbidden: + $ref: ./examples.yml#/Forbidden +NotFound: + description: >- + The object does not exist or is not visible to the caller; code + not_found. Missing and inaccessible objects are not distinguished. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + not_found: + $ref: ./examples.yml#/NotFound +IdempotencyInProgress: + description: >- + A request with the same Idempotency-Key and the same fingerprint is still + being processed; code idempotency_in_progress. Retry after the original + request completes. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + idempotency_in_progress: + $ref: ./examples.yml#/IdempotencyInProgress +StateConflict: + description: >- + The operation conflicts with the current state of the resource, for + example a transition that is not allowed from its current status; code + state_conflict. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/StateConflict +PreconditionFailed: + description: >- + If-Match does not match the current resource version; code + version_conflict. Nothing was changed. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + version_conflict: + $ref: ./examples.yml#/VersionConflict +PayloadTooLarge: + description: The request body exceeds the operation limit; code payload_too_large. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + payload_too_large: + $ref: ./examples.yml#/PayloadTooLarge +UnprocessableContent: + description: >- + The Idempotency-Key was already used with a different request within 24 + hours; code idempotency_key_reused. Nothing was changed. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + idempotency_key_reused: + $ref: ./examples.yml#/IdempotencyKeyReused +PreconditionRequired: + description: The operation requires If-Match; code precondition_required. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + precondition_required: + $ref: ./examples.yml#/PreconditionRequired +TooManyRequests: + description: Too many requests; code rate_limited. + headers: + Retry-After: + $ref: ./headers.yml#/RetryAfter + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + rate_limited: + $ref: ./examples.yml#/RateLimited +Internal: + description: Unexpected server error; code internal. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + internal: + $ref: ./examples.yml#/Internal +NotImplemented: + description: >- + The operation is declared in the contract but not implemented yet; code + not_implemented. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + not_implemented: + $ref: ./examples.yml#/NotImplemented +Problem: + description: >- + Any error response. The body is a Problem whose `status` equals the HTTP + status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + validation_failed: + $ref: ./examples.yml#/ValidationFailed + not_found: + $ref: ./examples.yml#/NotFound + internal: + $ref: ./examples.yml#/Internal + not_implemented: + $ref: ./examples.yml#/NotImplemented diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index c9e3a15..5dce273 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -1,3 +1,28 @@ +Timestamp: + type: string + format: date-time + description: UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema. + examples: + - '2026-10-05T09:30:00Z' +PageInfo: + type: object + description: Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`. + additionalProperties: false + required: + - has_more + - next_cursor + properties: + has_more: + type: boolean + description: Whether another page follows this one. + next_cursor: + type: + - string + - 'null' + minLength: 1 + maxLength: 512 + pattern: ^[A-Za-z0-9_-]+$ + description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing. HealthResponse: type: object additionalProperties: false @@ -8,3 +33,139 @@ HealthResponse: type: string enum: - ok +Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/ProblemFieldError' +ProblemCode: + type: string + description: 'Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + + - unauthenticated (401): no valid session or credentials. + + - forbidden (403): the caller is authenticated but not allowed. + + - not_found (404): the route or object does not exist or is not visible. + + - method_not_allowed (405): the route does not support the method. + + - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. + + - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. + + - version_conflict (412): If-Match does not match the current version. + + - payload_too_large (413): the request body exceeds the limit. + + - unsupported_media_type (415): the request Content-Type is not accepted. + + - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. + + - precondition_required (428): the operation requires If-Match. + + - rate_limited (429): too many requests; see Retry-After. + + - internal (500): unexpected server error. + + - not_implemented (501): the operation is in the contract but not implemented yet.' + enum: + - validation_failed + - unauthenticated + - forbidden + - not_found + - method_not_allowed + - idempotency_in_progress + - state_conflict + - version_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - precondition_required + - rate_limited + - internal + - not_implemented +ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. +ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie diff --git a/api/core/components/schemas/common_schemas.yml b/api/core/components/schemas/common_schemas.yml new file mode 100644 index 0000000..9bace9a --- /dev/null +++ b/api/core/components/schemas/common_schemas.yml @@ -0,0 +1,34 @@ +schemas: + Timestamp: + type: string + format: date-time + description: >- + UTC instant in RFC 3339 format with the Z suffix, for example + 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in + this contract uses this schema. + examples: + - "2026-10-05T09:30:00Z" + PageInfo: + type: object + description: >- + Cursor pagination state of a list response. Lists are ordered by a + stable server-defined key. To read the next page, repeat the request + with the same filters and `cursor` set to `next_cursor`. + additionalProperties: false + required: + - has_more + - next_cursor + properties: + has_more: + type: boolean + description: Whether another page follows this one. + next_cursor: + type: + - string + - "null" + minLength: 1 + maxLength: 512 + pattern: "^[A-Za-z0-9_-]+$" + description: >- + Opaque cursor of the next page, or null on the last page. Clients + must not parse, build, or store it beyond the current listing. diff --git a/api/core/components/schemas/problem_schemas.yml b/api/core/components/schemas/problem_schemas.yml new file mode 100644 index 0000000..dba3601 --- /dev/null +++ b/api/core/components/schemas/problem_schemas.yml @@ -0,0 +1,146 @@ +schemas: + Problem: + type: object + description: >- + Problem details (RFC 9457) returned with the application/problem+json + media type for every error response. `code` is the stable, + machine-readable reason; clients branch on it rather than on `title`, + `detail`, or the HTTP status alone. The body never contains internal + error text, stack traces, SQL, file paths, credentials, contact data, or + echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: >- + URI that identifies the problem type. It has the form + `urn:lincodex:problem:` and is an identifier, not a link to + dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: >- + Short, fixed English summary of the problem type. It does not change + between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: "#/schemas/ProblemCode" + detail: + type: string + maxLength: 1000 + description: >- + Safe English explanation of this occurrence. It never contains + internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Request identifier, equal to the X-Request-ID response header. Quote + it when reporting the problem; it is not a secret. + errors: + type: array + maxItems: 100 + description: >- + Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: "#/schemas/ProblemFieldError" + ProblemCode: + type: string + description: |- + Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - unauthenticated (401): no valid session or credentials. + - forbidden (403): the caller is authenticated but not allowed. + - not_found (404): the route or object does not exist or is not visible. + - method_not_allowed (405): the route does not support the method. + - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. + - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. + - version_conflict (412): If-Match does not match the current version. + - payload_too_large (413): the request body exceeds the limit. + - unsupported_media_type (415): the request Content-Type is not accepted. + - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. + - precondition_required (428): the operation requires If-Match. + - rate_limited (429): too many requests; see Retry-After. + - internal (500): unexpected server error. + - not_implemented (501): the operation is in the contract but not implemented yet. + enum: + - validation_failed + - unauthenticated + - forbidden + - not_found + - method_not_allowed + - idempotency_in_progress + - state_conflict + - version_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - precondition_required + - rate_limited + - internal + - not_implemented + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: "#/schemas/ProblemFieldLocation" + pointer: + type: string + maxLength: 1024 + pattern: "^(/([^~/]|~[01])*)*$" + description: >- + JSON Pointer (RFC 6901). For `body` it points into the request body + document, for example `/salary_from`; an empty string means the whole + body. For a parameter it is `/` followed by the parameter name, for + example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z][a-z0-9_]*$" + description: >- + Stable field reason. Current values are `required` (missing value) + and `invalid` (malformed value or a value outside the schema). + Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index cbc3fde..1d8ff51 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -19,8 +19,162 @@ paths: application/json: schema: $ref: '#/components/schemas/HealthResponse' + examples: + ok: + summary: The process is responding + value: + status: ok + default: + $ref: '#/components/responses/Problem' components: schemas: + Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/components/schemas/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/components/schemas/ProblemFieldError' + ProblemCode: + type: string + description: |- + Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - unauthenticated (401): no valid session or credentials. + - forbidden (403): the caller is authenticated but not allowed. + - not_found (404): the route or object does not exist or is not visible. + - method_not_allowed (405): the route does not support the method. + - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. + - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. + - version_conflict (412): If-Match does not match the current version. + - payload_too_large (413): the request body exceeds the limit. + - unsupported_media_type (415): the request Content-Type is not accepted. + - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. + - precondition_required (428): the operation requires If-Match. + - rate_limited (429): too many requests; see Retry-After. + - internal (500): unexpected server error. + - not_implemented (501): the operation is in the contract but not implemented yet. + enum: + - validation_failed + - unauthenticated + - forbidden + - not_found + - method_not_allowed + - idempotency_in_progress + - state_conflict + - version_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - precondition_required + - rate_limited + - internal + - not_implemented + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/components/schemas/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie + Timestamp: + type: string + format: date-time + description: UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema. + examples: + - '2026-10-05T09:30:00Z' + PageInfo: + type: object + description: Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`. + additionalProperties: false + required: + - has_more + - next_cursor + properties: + has_more: + type: boolean + description: Whether another page follows this one. + next_cursor: + type: + - string + - 'null' + minLength: 1 + maxLength: 512 + pattern: ^[A-Za-z0-9_-]+$ + description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing. HealthResponse: type: object additionalProperties: false @@ -31,3 +185,354 @@ components: type: string enum: - ok + parameters: + IdempotencyKey: + name: Idempotency-Key + in: header + required: true + description: |- + Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value is sent without quotes. The server scopes the key by caller and operation and fingerprints the request by method, path, and body. + + Stored for 24 hours after the first request and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 not_found or 409 state_conflict. A replay does not repeat the side effect. + + Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 precondition_required (nothing changed; read the resource again and retry), 422 idempotency_key_reused, 429, and every 5xx. + + Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused before any other key check; a running request with the same fingerprint returns 409 idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that does the server check If-Match, so a retry of a completed change replays its outcome instead of failing on the version it has just changed. After 24 hours the key may be accepted as new. + schema: + type: string + minLength: 1 + maxLength: 255 + pattern: ^[A-Za-z0-9._:-]+$ + example: 5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11 + IfMatch: + name: If-Match + in: header + required: false + description: |- + Strong entity tag of the resource version the client last read, copied from the ETag response header. An operation that changes a versioned resource says in its own description that it requires If-Match. + + On such an operation, a missing If-Match returns 428 precondition_required. An If-Match that does not equal the current ETag returns 412 version_conflict and changes nothing; read the resource again before retrying. Only one strong entity tag is accepted; weak tags, lists, and `*` fail validation with 400. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: ^"[A-Za-z0-9._~-]{1,128}"$ + example: '"v7"' + PageLimit: + name: limit + in: query + required: false + description: Maximum number of items in the page. The server may return fewer items even when more remain; use `page.has_more` to detect the end. + schema: + type: integer + format: int32 + minimum: 1 + maximum: 100 + default: 20 + PageCursor: + name: cursor + in: query + required: false + description: Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the first page. A malformed or foreign cursor returns 400 with code validation_failed. + schema: + type: string + minLength: 1 + maxLength: 512 + pattern: ^[A-Za-z0-9_-]+$ + headers: + ETag: + description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version. + required: true + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: ^"[A-Za-z0-9._~-]{1,128}"$ + example: '"v7"' + RetryAfter: + description: Number of seconds to wait before retrying the request. + schema: + type: integer + format: int32 + minimum: 0 + maximum: 86400 + example: 30 + responses: + ValidationFailed: + description: Parameters, headers, or the body do not match the contract, or the body violates a domain rule such as salary_from <= salary_to. The body has code validation_failed and lists the failing fields in `errors` with body or parameter pointers. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + validation_failed: + $ref: '#/components/examples/ValidationFailed' + domain_rule: + $ref: '#/components/examples/DomainValidationFailed' + Unauthenticated: + description: No valid session or credentials; code unauthenticated. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + unauthenticated: + $ref: '#/components/examples/Unauthenticated' + Forbidden: + description: The caller is authenticated but may not perform the operation; code forbidden. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + forbidden: + $ref: '#/components/examples/Forbidden' + NotFound: + description: The object does not exist or is not visible to the caller; code not_found. Missing and inaccessible objects are not distinguished. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + not_found: + $ref: '#/components/examples/NotFound' + IdempotencyInProgress: + description: A request with the same Idempotency-Key and the same fingerprint is still being processed; code idempotency_in_progress. Retry after the original request completes. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' + StateConflict: + description: The operation conflicts with the current state of the resource, for example a transition that is not allowed from its current status; code state_conflict. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/StateConflict' + PreconditionFailed: + description: If-Match does not match the current resource version; code version_conflict. Nothing was changed. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/VersionConflict' + PayloadTooLarge: + description: The request body exceeds the operation limit; code payload_too_large. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + payload_too_large: + $ref: '#/components/examples/PayloadTooLarge' + UnprocessableContent: + description: The Idempotency-Key was already used with a different request within 24 hours; code idempotency_key_reused. Nothing was changed. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + idempotency_key_reused: + $ref: '#/components/examples/IdempotencyKeyReused' + PreconditionRequired: + description: The operation requires If-Match; code precondition_required. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + precondition_required: + $ref: '#/components/examples/PreconditionRequired' + TooManyRequests: + description: Too many requests; code rate_limited. + headers: + Retry-After: + $ref: '#/components/headers/RetryAfter' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + rate_limited: + $ref: '#/components/examples/RateLimited' + Internal: + description: Unexpected server error; code internal. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + internal: + $ref: '#/components/examples/Internal' + NotImplemented: + description: The operation is declared in the contract but not implemented yet; code not_implemented. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + not_implemented: + $ref: '#/components/examples/NotImplemented' + Problem: + description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + validation_failed: + $ref: '#/components/examples/ValidationFailed' + not_found: + $ref: '#/components/examples/NotFound' + internal: + $ref: '#/components/examples/Internal' + not_implemented: + $ref: '#/components/examples/NotImplemented' + examples: + ValidationFailed: + summary: Request parameters do not match the contract + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10 + errors: + - in: query + pointer: /limit + code: invalid + message: The value does not match the contract. + - in: header + pointer: /Idempotency-Key + code: required + message: The value is required. + NotFound: + summary: Unknown route or invisible object + value: + type: urn:lincodex:problem:not_found + title: Resource not found + status: 404 + code: not_found + detail: The requested resource does not exist. + trace_id: 1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f + Internal: + summary: Unexpected server error + value: + type: urn:lincodex:problem:internal + title: Internal server error + status: 500 + code: internal + detail: The server could not complete the request. + trace_id: 9c0d1e2f-3a4b-4c5d-8e6f-7a8b9c0d1e2f + NotImplemented: + summary: Operation declared in the contract without an implementation + value: + type: urn:lincodex:problem:not_implemented + title: Operation not implemented + status: 501 + code: not_implemented + detail: This operation is not available yet. + trace_id: 0d1e2f3a-4b5c-4d6e-9f7a-8b9c0d1e2f3a + DomainValidationFailed: + summary: The body violates a domain rule + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 2f3a4b5c-6d7e-4f8a-9b0c-1d2e3f4a5b6c + errors: + - in: body + pointer: /salary_from + code: invalid + message: The value does not match the contract. + Unauthenticated: + summary: No valid session + value: + type: urn:lincodex:problem:unauthenticated + title: Authentication required + status: 401 + code: unauthenticated + detail: Sign in and repeat the request. + trace_id: 4f2d1c3b-6a5e-4d7f-8b9a-0c1d2e3f4a5b + Forbidden: + summary: The caller may not access the object + value: + type: urn:lincodex:problem:forbidden + title: Access denied + status: 403 + code: forbidden + detail: You do not have permission to perform this operation. + trace_id: 7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d + IdempotencyInProgress: + summary: The first request with this key is still running + value: + type: urn:lincodex:problem:idempotency_in_progress + title: Request with this idempotency key is in progress + status: 409 + code: idempotency_in_progress + detail: Retry after the original request completes. + trace_id: 2d3e4f5a-6b7c-4d8e-9f0a-1b2c3d4e5f6a + StateConflict: + summary: The resource state does not allow the operation + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b + VersionConflict: + summary: If-Match does not match the current version + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 3e4f5a6b-7c8d-4e9f-8a0b-2c3d4e5f6a7b + PayloadTooLarge: + summary: The request body exceeds the limit + value: + type: urn:lincodex:problem:payload_too_large + title: Request body too large + status: 413 + code: payload_too_large + detail: Reduce the request body size and retry. + trace_id: 8b9c0d1e-2f3a-4b4c-9d5e-6f7a8b9c0d1e + IdempotencyKeyReused: + summary: The same Idempotency-Key was sent with a different body + value: + type: urn:lincodex:problem:idempotency_key_reused + title: Idempotency key reused with a different request + status: 422 + code: idempotency_key_reused + detail: Use a new Idempotency-Key for a different request. + trace_id: 4f5a6b7c-8d9e-4f0a-9b1c-3d4e5f6a7b8c + PreconditionRequired: + summary: The operation requires If-Match + value: + type: urn:lincodex:problem:precondition_required + title: Precondition required + status: 428 + code: precondition_required + detail: Send If-Match with the ETag of the version you read. + trace_id: 5a6b7c8d-9e0f-4a1b-8c2d-4e5f6a7b8c9d + RateLimited: + summary: Too many requests + value: + type: urn:lincodex:problem:rate_limited + title: Too many requests + status: 429 + code: rate_limited + detail: Wait for the Retry-After interval and retry. + trace_id: 6b7c8d9e-0f1a-4b2c-9d3e-5f6a7b8c9d0e diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 0b97e09..2c0d003 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -7,3 +7,60 @@ servers: paths: /api/v1/healthz: $ref: ./routes/healthz.yml +components: + schemas: + Problem: + $ref: ./components/schemas.yml#/Problem + ProblemCode: + $ref: ./components/schemas.yml#/ProblemCode + ProblemFieldError: + $ref: ./components/schemas.yml#/ProblemFieldError + ProblemFieldLocation: + $ref: ./components/schemas.yml#/ProblemFieldLocation + Timestamp: + $ref: ./components/schemas.yml#/Timestamp + PageInfo: + $ref: ./components/schemas.yml#/PageInfo + parameters: + IdempotencyKey: + $ref: ./components/parameters.yml#/IdempotencyKey + IfMatch: + $ref: ./components/parameters.yml#/IfMatch + PageLimit: + $ref: ./components/parameters.yml#/PageLimit + PageCursor: + $ref: ./components/parameters.yml#/PageCursor + headers: + ETag: + $ref: ./components/headers.yml#/ETag + RetryAfter: + $ref: ./components/headers.yml#/RetryAfter + responses: + ValidationFailed: + $ref: ./components/responses.yml#/ValidationFailed + Unauthenticated: + $ref: ./components/responses.yml#/Unauthenticated + Forbidden: + $ref: ./components/responses.yml#/Forbidden + NotFound: + $ref: ./components/responses.yml#/NotFound + IdempotencyInProgress: + $ref: ./components/responses.yml#/IdempotencyInProgress + StateConflict: + $ref: ./components/responses.yml#/StateConflict + PreconditionFailed: + $ref: ./components/responses.yml#/PreconditionFailed + PayloadTooLarge: + $ref: ./components/responses.yml#/PayloadTooLarge + UnprocessableContent: + $ref: ./components/responses.yml#/UnprocessableContent + PreconditionRequired: + $ref: ./components/responses.yml#/PreconditionRequired + TooManyRequests: + $ref: ./components/responses.yml#/TooManyRequests + Internal: + $ref: ./components/responses.yml#/Internal + NotImplemented: + $ref: ./components/responses.yml#/NotImplemented + Problem: + $ref: ./components/responses.yml#/Problem diff --git a/api/core/routes/healthz.yml b/api/core/routes/healthz.yml index a006981..03a25c3 100644 --- a/api/core/routes/healthz.yml +++ b/api/core/routes/healthz.yml @@ -11,3 +11,10 @@ get: application/json: schema: $ref: ../components/schemas.yml#/HealthResponse + examples: + ok: + summary: The process is responding + value: + status: ok + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/ml/components/responses.yml b/api/ml/components/responses.yml new file mode 100644 index 0000000..1e3361d --- /dev/null +++ b/api/ml/components/responses.yml @@ -0,0 +1,30 @@ +Problem: + description: >- + Any error response. The body is a Problem whose `status` equals the HTTP + status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + validation_failed: + summary: Request parameters do not match the contract + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + errors: + - in: query + pointer: /limit + code: invalid + message: The value does not match the contract. + internal: + summary: Unexpected server error + value: + type: urn:lincodex:problem:internal + title: Internal server error + status: 500 + code: internal + detail: The server could not complete the request. diff --git a/api/ml/components/schemas.yml b/api/ml/components/schemas.yml index b853c09..28759b6 100644 --- a/api/ml/components/schemas.yml +++ b/api/ml/components/schemas.yml @@ -8,6 +8,142 @@ MLHealthResponse: type: string enum: - ok +Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the ML service copy of the public api/core Problem schema; keep both copies identical except for descriptions. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/ProblemFieldError' +ProblemCode: + type: string + description: 'Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + + - unauthenticated (401): no valid session or credentials. + + - forbidden (403): the caller is authenticated but not allowed. + + - not_found (404): the route or object does not exist or is not visible. + + - method_not_allowed (405): the route does not support the method. + + - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. + + - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. + + - version_conflict (412): If-Match does not match the current version. + + - payload_too_large (413): the request body exceeds the limit. + + - unsupported_media_type (415): the request Content-Type is not accepted. + + - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. + + - precondition_required (428): the operation requires If-Match. + + - rate_limited (429): too many requests; see Retry-After. + + - internal (500): unexpected server error. + + - not_implemented (501): the operation is in the contract but not implemented yet.' + enum: + - validation_failed + - unauthenticated + - forbidden + - not_found + - method_not_allowed + - idempotency_in_progress + - state_conflict + - version_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - precondition_required + - rate_limited + - internal + - not_implemented +ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. +ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie MLReadinessResponse: type: object additionalProperties: false diff --git a/api/ml/components/schemas/problem_schemas.yml b/api/ml/components/schemas/problem_schemas.yml new file mode 100644 index 0000000..0147d38 --- /dev/null +++ b/api/ml/components/schemas/problem_schemas.yml @@ -0,0 +1,148 @@ +schemas: + Problem: + type: object + description: >- + Problem details (RFC 9457) returned with the application/problem+json + media type for every error response. This is the ML service copy of the + public api/core Problem schema; keep both copies identical except for + descriptions. `code` is the stable, + machine-readable reason; clients branch on it rather than on `title`, + `detail`, or the HTTP status alone. The body never contains internal + error text, stack traces, SQL, file paths, credentials, contact data, or + echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: >- + URI that identifies the problem type. It has the form + `urn:lincodex:problem:` and is an identifier, not a link to + dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: >- + Short, fixed English summary of the problem type. It does not change + between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: "#/schemas/ProblemCode" + detail: + type: string + maxLength: 1000 + description: >- + Safe English explanation of this occurrence. It never contains + internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Request identifier of the call when the caller propagated one; it is + not a secret. + errors: + type: array + maxItems: 100 + description: >- + Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: "#/schemas/ProblemFieldError" + ProblemCode: + type: string + description: |- + Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - unauthenticated (401): no valid session or credentials. + - forbidden (403): the caller is authenticated but not allowed. + - not_found (404): the route or object does not exist or is not visible. + - method_not_allowed (405): the route does not support the method. + - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. + - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. + - version_conflict (412): If-Match does not match the current version. + - payload_too_large (413): the request body exceeds the limit. + - unsupported_media_type (415): the request Content-Type is not accepted. + - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. + - precondition_required (428): the operation requires If-Match. + - rate_limited (429): too many requests; see Retry-After. + - internal (500): unexpected server error. + - not_implemented (501): the operation is in the contract but not implemented yet. + enum: + - validation_failed + - unauthenticated + - forbidden + - not_found + - method_not_allowed + - idempotency_in_progress + - state_conflict + - version_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - precondition_required + - rate_limited + - internal + - not_implemented + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: "#/schemas/ProblemFieldLocation" + pointer: + type: string + maxLength: 1024 + pattern: "^(/([^~/]|~[01])*)*$" + description: >- + JSON Pointer (RFC 6901). For `body` it points into the request body + document, for example `/salary_from`; an empty string means the whole + body. For a parameter it is `/` followed by the parameter name, for + example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z][a-z0-9_]*$" + description: >- + Stable field reason. Current values are `required` (missing value) + and `invalid` (malformed value or a value outside the schema). + Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie diff --git a/api/ml/openapi.bundle.yml b/api/ml/openapi.bundle.yml index 300e18f..503c1eb 100644 --- a/api/ml/openapi.bundle.yml +++ b/api/ml/openapi.bundle.yml @@ -19,6 +19,8 @@ paths: application/json: schema: $ref: '#/components/schemas/MLHealthResponse' + default: + $ref: '#/components/responses/Problem' /readyz: get: operationId: GetMLReadyz @@ -39,8 +41,161 @@ paths: application/json: schema: $ref: '#/components/schemas/MLReadinessResponse' + default: + $ref: '#/components/responses/Problem' components: + responses: + Problem: + description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + validation_failed: + summary: Request parameters do not match the contract + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + errors: + - in: query + pointer: /limit + code: invalid + message: The value does not match the contract. + internal: + summary: Unexpected server error + value: + type: urn:lincodex:problem:internal + title: Internal server error + status: 500 + code: internal + detail: The server could not complete the request. schemas: + ProblemCode: + type: string + description: |- + Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - unauthenticated (401): no valid session or credentials. + - forbidden (403): the caller is authenticated but not allowed. + - not_found (404): the route or object does not exist or is not visible. + - method_not_allowed (405): the route does not support the method. + - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. + - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. + - version_conflict (412): If-Match does not match the current version. + - payload_too_large (413): the request body exceeds the limit. + - unsupported_media_type (415): the request Content-Type is not accepted. + - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. + - precondition_required (428): the operation requires If-Match. + - rate_limited (429): too many requests; see Retry-After. + - internal (500): unexpected server error. + - not_implemented (501): the operation is in the contract but not implemented yet. + enum: + - validation_failed + - unauthenticated + - forbidden + - not_found + - method_not_allowed + - idempotency_in_progress + - state_conflict + - version_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - precondition_required + - rate_limited + - internal + - not_implemented + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/components/schemas/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the ML service copy of the public api/core Problem schema; keep both copies identical except for descriptions. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/components/schemas/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/components/schemas/ProblemFieldError' MLHealthResponse: type: object additionalProperties: false diff --git a/api/ml/openapi.yml b/api/ml/openapi.yml index f9bd5c8..103ba29 100644 --- a/api/ml/openapi.yml +++ b/api/ml/openapi.yml @@ -9,3 +9,7 @@ paths: $ref: ./routes/healthz.yml /readyz: $ref: ./routes/readyz.yml +components: + responses: + Problem: + $ref: ./components/responses.yml#/Problem diff --git a/api/ml/routes/healthz.yml b/api/ml/routes/healthz.yml index 77f1350..a262e03 100644 --- a/api/ml/routes/healthz.yml +++ b/api/ml/routes/healthz.yml @@ -11,3 +11,5 @@ get: application/json: schema: $ref: ../components/schemas.yml#/MLHealthResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/ml/routes/readyz.yml b/api/ml/routes/readyz.yml index deeccc7..fa2aa4b 100644 --- a/api/ml/routes/readyz.yml +++ b/api/ml/routes/readyz.yml @@ -17,3 +17,5 @@ get: application/json: schema: $ref: ../components/schemas.yml#/MLReadinessResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/testdata/openapi-3.2.0.yml b/api/testdata/openapi-3.2.0.yml index eb54a12..8573da0 100644 --- a/api/testdata/openapi-3.2.0.yml +++ b/api/testdata/openapi-3.2.0.yml @@ -2,6 +2,12 @@ openapi: 3.2.0 info: title: OpenAPI 3.2 compatibility fixture version: 0.1.0 + description: >- + Exercises the OpenAPI 3.2 subset and the api/core conventions (problem + details, cursor pagination, Idempotency-Key, If-Match, and ETag) through + the pinned generators. The operations are test fixtures, not product + endpoints. Component definitions shared with api/core are copies that must + stay identical to the api/core bundle. servers: - url: / paths: @@ -25,6 +31,8 @@ paths: application/json: schema: $ref: "#/components/schemas/NullablePayload" + default: + $ref: "#/components/responses/Problem" additionalOperations: PURGE: operationId: PurgeProbe @@ -33,6 +41,90 @@ paths: responses: "204": description: The compatibility fixture operation completed. + default: + $ref: "#/components/responses/Problem" + /probe/items: + get: + operationId: ListProbeItems + summary: Exercise bounded cursor pagination. + security: [] + parameters: + - $ref: "#/components/parameters/PageLimit" + - $ref: "#/components/parameters/PageCursor" + responses: + "200": + description: One page of fixture items. + content: + application/json: + schema: + $ref: "#/components/schemas/ProbeItemPage" + default: + $ref: "#/components/responses/Problem" + post: + operationId: CreateProbeItem + summary: Exercise an idempotent mutating command. + security: [] + parameters: + - $ref: "#/components/parameters/IdempotencyKey" + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ProbeItemInput" + responses: + "201": + description: The fixture item was created or the stored response was replayed. + headers: + ETag: + $ref: "#/components/headers/ETag" + content: + application/json: + schema: + $ref: "#/components/schemas/ProbeItem" + "409": + $ref: "#/components/responses/IdempotencyInProgress" + "422": + $ref: "#/components/responses/UnprocessableContent" + default: + $ref: "#/components/responses/Problem" + /probe/items/{item_id}: + patch: + operationId: UpdateProbeItem + summary: Exercise optimistic concurrency with If-Match and ETag. + description: This operation requires If-Match; without it the fixture handler answers 428 precondition_required. + security: [] + parameters: + - name: item_id + in: path + required: true + schema: + type: string + format: uuid + - $ref: "#/components/parameters/IdempotencyKey" + - $ref: "#/components/parameters/IfMatch" + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ProbeItemInput" + responses: + "200": + description: The fixture item was updated. + headers: + ETag: + $ref: "#/components/headers/ETag" + content: + application/json: + schema: + $ref: "#/components/schemas/ProbeItem" + "412": + $ref: "#/components/responses/PreconditionFailed" + "428": + $ref: "#/components/responses/PreconditionRequired" + default: + $ref: "#/components/responses/Problem" components: schemas: NullablePayload: @@ -45,3 +137,305 @@ components: type: - string - "null" + ProbeItemInput: + type: object + additionalProperties: false + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 100 + ProbeItem: + type: object + additionalProperties: false + required: + - id + - name + - updated_at + properties: + id: + type: string + format: uuid + name: + type: string + minLength: 1 + maxLength: 100 + updated_at: + $ref: "#/components/schemas/Timestamp" + ProbeItemPage: + type: object + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + items: + $ref: "#/components/schemas/ProbeItem" + page: + $ref: "#/components/schemas/PageInfo" + Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: "#/components/schemas/ProblemCode" + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: "#/components/schemas/ProblemFieldError" + ProblemCode: + type: string + description: + "Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + + - unauthenticated (401): no valid session or credentials. + + - forbidden (403): the caller is authenticated but not allowed. + + - not_found (404): the route or object does not exist or is not visible. + + - method_not_allowed (405): the route does not support the method. + + - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. + + - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. + + - version_conflict (412): If-Match does not match the current version. + + - payload_too_large (413): the request body exceeds the limit. + + - unsupported_media_type (415): the request Content-Type is not accepted. + + - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. + + - precondition_required (428): the operation requires If-Match. + + - rate_limited (429): too many requests; see Retry-After. + + - internal (500): unexpected server error. + + - not_implemented (501): the operation is in the contract but not implemented yet." + enum: + - validation_failed + - unauthenticated + - forbidden + - not_found + - method_not_allowed + - idempotency_in_progress + - state_conflict + - version_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - precondition_required + - rate_limited + - internal + - not_implemented + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: "#/components/schemas/ProblemFieldLocation" + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie + Timestamp: + type: string + format: date-time + description: UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema. + examples: + - "2026-10-05T09:30:00Z" + PageInfo: + type: object + description: Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`. + additionalProperties: false + required: + - has_more + - next_cursor + properties: + has_more: + type: boolean + description: Whether another page follows this one. + next_cursor: + type: + - string + - "null" + minLength: 1 + maxLength: 512 + pattern: ^[A-Za-z0-9_-]+$ + description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing. + parameters: + IdempotencyKey: + name: Idempotency-Key + in: header + required: true + description: + "Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value is sent without quotes. The server scopes the key by caller and operation and fingerprints the request by method, path, and body. + + + Stored for 24 hours after the first request and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 not_found or 409 state_conflict. A replay does not repeat the side effect. + + + Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 precondition_required (nothing changed; read the resource again and retry), 422 idempotency_key_reused, 429, and every 5xx. + + + Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused before any other key check; a running request with the same fingerprint returns 409 idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that does the server check If-Match, so a retry of a completed change replays its outcome instead of failing on the version it has just changed. After 24 hours the key may be accepted as new." + schema: + type: string + minLength: 1 + maxLength: 255 + pattern: ^[A-Za-z0-9._:-]+$ + example: 5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11 + IfMatch: + name: If-Match + in: header + required: false + description: + "Strong entity tag of the resource version the client last read, copied from the ETag response header. An operation that changes a versioned resource says in its own description that it requires If-Match. + + + On such an operation, a missing If-Match returns 428 precondition_required. An If-Match that does not equal the current ETag returns 412 version_conflict and changes nothing; read the resource again before retrying. Only one strong entity tag is accepted; weak tags, lists, and `*` fail validation with 400. The parameter is optional in the schema so that a missing header reaches the application, which answers 428." + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: ^"[A-Za-z0-9._~-]{1,128}"$ + example: '"v7"' + PageLimit: + name: limit + in: query + required: false + description: Maximum number of items in the page. The server may return fewer items even when more remain; use `page.has_more` to detect the end. + schema: + type: integer + format: int32 + minimum: 1 + maximum: 100 + default: 20 + PageCursor: + name: cursor + in: query + required: false + description: Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the first page. A malformed or foreign cursor returns 400 with code validation_failed. + schema: + type: string + minLength: 1 + maxLength: 512 + pattern: ^[A-Za-z0-9_-]+$ + headers: + ETag: + description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version. + required: true + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: ^"[A-Za-z0-9._~-]{1,128}"$ + example: '"v7"' + responses: + IdempotencyInProgress: + description: A request with the same Idempotency-Key and the same fingerprint is still being processed; code idempotency_in_progress. Retry after the original request completes. + content: + application/problem+json: + schema: + $ref: "#/components/schemas/Problem" + UnprocessableContent: + description: The Idempotency-Key was already used with a different request within 24 hours; code idempotency_key_reused. Nothing was changed. + content: + application/problem+json: + schema: + $ref: "#/components/schemas/Problem" + PreconditionFailed: + description: If-Match does not match the current resource version; code version_conflict. Nothing was changed. + content: + application/problem+json: + schema: + $ref: "#/components/schemas/Problem" + PreconditionRequired: + description: The operation requires If-Match; code precondition_required. + content: + application/problem+json: + schema: + $ref: "#/components/schemas/Problem" + Problem: + description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: "#/components/schemas/Problem" diff --git a/backend/Makefile b/backend/Makefile index 4429afc..21e55ff 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -79,7 +79,7 @@ mocks: ## Generate configured mocks when interfaces are selected fi .PHONY: check-ogen-compat -check-ogen-compat: ## Verify OpenAPI 3.2 nullable values, validation, and additionalOperations +check-ogen-compat: ## Verify OpenAPI 3.2 features and API error, pagination, and retry conventions with ogen @set -euo pipefail; mkdir -p bin; temporary_dir=$$(mktemp -d "$(CURDIR)/bin/ogen-compat.XXXXXX"); trap 'rm -rf "$$temporary_dir"' EXIT; \ $(GO_TOOL) ogen -config codegen/ogen-compat.yml --target "$$temporary_dir" --package compat --clean ../api/testdata/openapi-3.2.0.yml; \ cp testdata/ogen_compat_test.go "$$temporary_dir/ogen_compat_test.go"; \ diff --git a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go index 50146e0..39d14c1 100644 --- a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go @@ -8,6 +8,7 @@ import ( "github.com/ogen-go/ogen/middleware" "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/ogenregex" "github.com/ogen-go/ogen/otelogen" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" @@ -15,6 +16,11 @@ import ( "go.opentelemetry.io/otel/trace" ) +var regexMap = map[string]ogenregex.Regexp{ + "^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"), + "^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"), + "^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"), +} var ( // Allocate option closure once. serverSpanKind = trace.WithSpanKind(trace.SpanKindServer) diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index e8e2c77..dd06272 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -142,8 +142,19 @@ func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w htt response, err = s.h.GetHealthz(ctx) } if err != nil { - defer recordError("Internal", err) - s.cfg.ErrorHandler(ctx, w, r, err) + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } return } diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index 7edde1e..7688eca 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -142,3 +142,519 @@ func (s *HealthResponseStatus) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } + +// Encode encodes string as json. +func (o OptString) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Str(string(o.Value)) +} + +// Decode decodes string from json. +func (o *OptString) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptString to nil") + } + o.Set = true + v, err := d.Str() + if err != nil { + return err + } + o.Value = string(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptString) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptString) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *Problem) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Problem) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + e.Str(s.Type) + } + { + e.FieldStart("title") + e.Str(s.Title) + } + { + e.FieldStart("status") + e.Int32(s.Status) + } + { + e.FieldStart("code") + s.Code.Encode(e) + } + { + if s.Detail.Set { + e.FieldStart("detail") + s.Detail.Encode(e) + } + } + { + if s.Instance.Set { + e.FieldStart("instance") + s.Instance.Encode(e) + } + } + { + if s.TraceID.Set { + e.FieldStart("trace_id") + s.TraceID.Encode(e) + } + } + { + if s.Errors != nil { + e.FieldStart("errors") + e.ArrStart() + for _, elem := range s.Errors { + elem.Encode(e) + } + e.ArrEnd() + } + } +} + +var jsonFieldsNameOfProblem = [8]string{ + 0: "type", + 1: "title", + 2: "status", + 3: "code", + 4: "detail", + 5: "instance", + 6: "trace_id", + 7: "errors", +} + +// Decode decodes Problem from json. +func (s *Problem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Problem to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Type = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "title": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Title = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"title\"") + } + case "status": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.Status = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "code": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Code.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "detail": + if err := func() error { + s.Detail.Reset() + if err := s.Detail.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"detail\"") + } + case "instance": + if err := func() error { + s.Instance.Reset() + if err := s.Instance.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"instance\"") + } + case "trace_id": + if err := func() error { + s.TraceID.Reset() + if err := s.TraceID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"trace_id\"") + } + case "errors": + if err := func() error { + s.Errors = make([]ProblemFieldError, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProblemFieldError + if err := elem.Decode(d); err != nil { + return err + } + s.Errors = append(s.Errors, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"errors\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Problem") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProblem) { + name = jsonFieldsNameOfProblem[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *Problem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Problem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProblemCode as json. +func (s ProblemCode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProblemCode from json. +func (s *ProblemCode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemCode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProblemCode(v) { + case ProblemCodeValidationFailed: + *s = ProblemCodeValidationFailed + case ProblemCodeUnauthenticated: + *s = ProblemCodeUnauthenticated + case ProblemCodeForbidden: + *s = ProblemCodeForbidden + case ProblemCodeNotFound: + *s = ProblemCodeNotFound + case ProblemCodeMethodNotAllowed: + *s = ProblemCodeMethodNotAllowed + case ProblemCodeIdempotencyInProgress: + *s = ProblemCodeIdempotencyInProgress + case ProblemCodeStateConflict: + *s = ProblemCodeStateConflict + case ProblemCodeVersionConflict: + *s = ProblemCodeVersionConflict + case ProblemCodePayloadTooLarge: + *s = ProblemCodePayloadTooLarge + case ProblemCodeUnsupportedMediaType: + *s = ProblemCodeUnsupportedMediaType + case ProblemCodeIdempotencyKeyReused: + *s = ProblemCodeIdempotencyKeyReused + case ProblemCodePreconditionRequired: + *s = ProblemCodePreconditionRequired + case ProblemCodeRateLimited: + *s = ProblemCodeRateLimited + case ProblemCodeInternal: + *s = ProblemCodeInternal + case ProblemCodeNotImplemented: + *s = ProblemCodeNotImplemented + default: + *s = ProblemCode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProblemCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProblemFieldError) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProblemFieldError) encodeFields(e *jx.Encoder) { + { + e.FieldStart("in") + s.In.Encode(e) + } + { + e.FieldStart("pointer") + e.Str(s.Pointer) + } + { + e.FieldStart("code") + e.Str(s.Code) + } + { + e.FieldStart("message") + e.Str(s.Message) + } +} + +var jsonFieldsNameOfProblemFieldError = [4]string{ + 0: "in", + 1: "pointer", + 2: "code", + 3: "message", +} + +// Decode decodes ProblemFieldError from json. +func (s *ProblemFieldError) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemFieldError to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "in": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.In.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"in\"") + } + case "pointer": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Pointer = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"pointer\"") + } + case "code": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.Code = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "message": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Str() + s.Message = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"message\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProblemFieldError") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProblemFieldError) { + name = jsonFieldsNameOfProblemFieldError[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProblemFieldError) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemFieldError) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProblemFieldLocation as json. +func (s ProblemFieldLocation) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProblemFieldLocation from json. +func (s *ProblemFieldLocation) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemFieldLocation to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProblemFieldLocation(v) { + case ProblemFieldLocationBody: + *s = ProblemFieldLocationBody + case ProblemFieldLocationQuery: + *s = ProblemFieldLocationQuery + case ProblemFieldLocationPath: + *s = ProblemFieldLocationPath + case ProblemFieldLocationHeader: + *s = ProblemFieldLocationHeader + case ProblemFieldLocationCookie: + *s = ProblemFieldLocationCookie + default: + *s = ProblemFieldLocation(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProblemFieldLocation) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemFieldLocation) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index 3974db8..aeaf05b 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -7,6 +7,8 @@ import ( "github.com/go-faster/errors" "github.com/go-faster/jx" + ht "github.com/ogen-go/ogen/http" + "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" ) @@ -22,3 +24,28 @@ func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, s return nil } + +func encodeErrorResponse(response *ProblemStatusCode, w http.ResponseWriter, span trace.Span) error { + w.Header().Set("Content-Type", "application/problem+json") + code := response.StatusCode + if code == 0 { + // Set default status code. + code = http.StatusOK + } + w.WriteHeader(code) + if code >= http.StatusInternalServerError { + span.SetStatus(codes.Error, http.StatusText(code)) + } + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + if code >= http.StatusInternalServerError { + return errors.Wrapf(ht.ErrInternalServerErrorResponse, "code: %d, message: %s", code, http.StatusText(code)) + } + return nil + +} diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index 9b7ceda..ad772c7 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -3,9 +3,15 @@ package api import ( + "fmt" + "github.com/go-faster/errors" ) +func (s *ProblemStatusCode) Error() string { + return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response) +} + // Ref: #/components/schemas/HealthResponse type HealthResponse struct { Status HealthResponseStatus `json:"status"` @@ -54,3 +60,454 @@ func (s *HealthResponseStatus) UnmarshalText(data []byte) error { return errors.Errorf("invalid value: %q", data) } } + +// NewOptString returns new OptString with value set to v. +func NewOptString(v string) OptString { + return OptString{ + Value: v, + Set: true, + } +} + +// OptString is optional string. +type OptString struct { + Value string + Set bool +} + +// IsSet returns true if OptString was set. +func (o OptString) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptString) Reset() { + var v string + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptString) SetTo(v string) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptString) Get() (v string, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptString) Or(d string) string { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// Problem details (RFC 9457) returned with the application/problem+json media type for every error +// response. `code` is the stable, machine-readable reason; clients branch on it rather than on +// `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack +// traces, SQL, file paths, credentials, contact data, or echoed request values. +// Ref: #/components/schemas/Problem +type Problem struct { + // URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an + // identifier, not a link to dereference. + Type string `json:"type"` + // Short, fixed English summary of the problem type. It does not change between occurrences. + Title string `json:"title"` + // HTTP status code generated by the origin server. + Status int32 `json:"status"` + Code ProblemCode `json:"code"` + // Safe English explanation of this occurrence. It never contains internal error text or request + // values. + Detail OptString `json:"detail"` + // URI reference that identifies this occurrence, when one exists. + Instance OptString `json:"instance"` + // Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; + // it is not a secret. + TraceID OptString `json:"trace_id"` + // Field-level reasons for validation_failed. Other codes omit it. + Errors []ProblemFieldError `json:"errors"` +} + +// GetType returns the value of Type. +func (s *Problem) GetType() string { + return s.Type +} + +// GetTitle returns the value of Title. +func (s *Problem) GetTitle() string { + return s.Title +} + +// GetStatus returns the value of Status. +func (s *Problem) GetStatus() int32 { + return s.Status +} + +// GetCode returns the value of Code. +func (s *Problem) GetCode() ProblemCode { + return s.Code +} + +// GetDetail returns the value of Detail. +func (s *Problem) GetDetail() OptString { + return s.Detail +} + +// GetInstance returns the value of Instance. +func (s *Problem) GetInstance() OptString { + return s.Instance +} + +// GetTraceID returns the value of TraceID. +func (s *Problem) GetTraceID() OptString { + return s.TraceID +} + +// GetErrors returns the value of Errors. +func (s *Problem) GetErrors() []ProblemFieldError { + return s.Errors +} + +// SetType sets the value of Type. +func (s *Problem) SetType(val string) { + s.Type = val +} + +// SetTitle sets the value of Title. +func (s *Problem) SetTitle(val string) { + s.Title = val +} + +// SetStatus sets the value of Status. +func (s *Problem) SetStatus(val int32) { + s.Status = val +} + +// SetCode sets the value of Code. +func (s *Problem) SetCode(val ProblemCode) { + s.Code = val +} + +// SetDetail sets the value of Detail. +func (s *Problem) SetDetail(val OptString) { + s.Detail = val +} + +// SetInstance sets the value of Instance. +func (s *Problem) SetInstance(val OptString) { + s.Instance = val +} + +// SetTraceID sets the value of TraceID. +func (s *Problem) SetTraceID(val OptString) { + s.TraceID = val +} + +// SetErrors sets the value of Errors. +func (s *Problem) SetErrors(val []ProblemFieldError) { + s.Errors = val +} + +// Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking +// change. Clients must handle an unknown code by its HTTP status. +// +// - validation_failed (400): parameters or body do not match the contract, or a body violates a +// domain rule such as salary_from <= salary_to; `errors` points at the fields. +// - unauthenticated (401): no valid session or credentials. +// - forbidden (403): the caller is authenticated but not allowed. +// - not_found (404): the route or object does not exist or is not visible. +// - method_not_allowed (405): the route does not support the method. +// - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. +// - state_conflict (409): the operation conflicts with the current state of the resource, for example +// an invitation that was already accepted. +// - version_conflict (412): If-Match does not match the current version. +// - payload_too_large (413): the request body exceeds the limit. +// - unsupported_media_type (415): the request Content-Type is not accepted. +// - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. +// - precondition_required (428): the operation requires If-Match. +// - rate_limited (429): too many requests; see Retry-After. +// - internal (500): unexpected server error. +// - not_implemented (501): the operation is in the contract but not implemented yet. +// +// Ref: #/components/schemas/ProblemCode +type ProblemCode string + +const ( + ProblemCodeValidationFailed ProblemCode = "validation_failed" + ProblemCodeUnauthenticated ProblemCode = "unauthenticated" + ProblemCodeForbidden ProblemCode = "forbidden" + ProblemCodeNotFound ProblemCode = "not_found" + ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed" + ProblemCodeIdempotencyInProgress ProblemCode = "idempotency_in_progress" + ProblemCodeStateConflict ProblemCode = "state_conflict" + ProblemCodeVersionConflict ProblemCode = "version_conflict" + ProblemCodePayloadTooLarge ProblemCode = "payload_too_large" + ProblemCodeUnsupportedMediaType ProblemCode = "unsupported_media_type" + ProblemCodeIdempotencyKeyReused ProblemCode = "idempotency_key_reused" + ProblemCodePreconditionRequired ProblemCode = "precondition_required" + ProblemCodeRateLimited ProblemCode = "rate_limited" + ProblemCodeInternal ProblemCode = "internal" + ProblemCodeNotImplemented ProblemCode = "not_implemented" +) + +// AllValues returns all ProblemCode values. +func (ProblemCode) AllValues() []ProblemCode { + return []ProblemCode{ + ProblemCodeValidationFailed, + ProblemCodeUnauthenticated, + ProblemCodeForbidden, + ProblemCodeNotFound, + ProblemCodeMethodNotAllowed, + ProblemCodeIdempotencyInProgress, + ProblemCodeStateConflict, + ProblemCodeVersionConflict, + ProblemCodePayloadTooLarge, + ProblemCodeUnsupportedMediaType, + ProblemCodeIdempotencyKeyReused, + ProblemCodePreconditionRequired, + ProblemCodeRateLimited, + ProblemCodeInternal, + ProblemCodeNotImplemented, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProblemCode) MarshalText() ([]byte, error) { + switch s { + case ProblemCodeValidationFailed: + return []byte(s), nil + case ProblemCodeUnauthenticated: + return []byte(s), nil + case ProblemCodeForbidden: + return []byte(s), nil + case ProblemCodeNotFound: + return []byte(s), nil + case ProblemCodeMethodNotAllowed: + return []byte(s), nil + case ProblemCodeIdempotencyInProgress: + return []byte(s), nil + case ProblemCodeStateConflict: + return []byte(s), nil + case ProblemCodeVersionConflict: + return []byte(s), nil + case ProblemCodePayloadTooLarge: + return []byte(s), nil + case ProblemCodeUnsupportedMediaType: + return []byte(s), nil + case ProblemCodeIdempotencyKeyReused: + return []byte(s), nil + case ProblemCodePreconditionRequired: + return []byte(s), nil + case ProblemCodeRateLimited: + return []byte(s), nil + case ProblemCodeInternal: + return []byte(s), nil + case ProblemCodeNotImplemented: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProblemCode) UnmarshalText(data []byte) error { + switch ProblemCode(data) { + case ProblemCodeValidationFailed: + *s = ProblemCodeValidationFailed + return nil + case ProblemCodeUnauthenticated: + *s = ProblemCodeUnauthenticated + return nil + case ProblemCodeForbidden: + *s = ProblemCodeForbidden + return nil + case ProblemCodeNotFound: + *s = ProblemCodeNotFound + return nil + case ProblemCodeMethodNotAllowed: + *s = ProblemCodeMethodNotAllowed + return nil + case ProblemCodeIdempotencyInProgress: + *s = ProblemCodeIdempotencyInProgress + return nil + case ProblemCodeStateConflict: + *s = ProblemCodeStateConflict + return nil + case ProblemCodeVersionConflict: + *s = ProblemCodeVersionConflict + return nil + case ProblemCodePayloadTooLarge: + *s = ProblemCodePayloadTooLarge + return nil + case ProblemCodeUnsupportedMediaType: + *s = ProblemCodeUnsupportedMediaType + return nil + case ProblemCodeIdempotencyKeyReused: + *s = ProblemCodeIdempotencyKeyReused + return nil + case ProblemCodePreconditionRequired: + *s = ProblemCodePreconditionRequired + return nil + case ProblemCodeRateLimited: + *s = ProblemCodeRateLimited + return nil + case ProblemCodeInternal: + *s = ProblemCodeInternal + return nil + case ProblemCodeNotImplemented: + *s = ProblemCodeNotImplemented + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One reason why a request field or parameter is invalid. +// Ref: #/components/schemas/ProblemFieldError +type ProblemFieldError struct { + In ProblemFieldLocation `json:"in"` + // JSON Pointer (RFC 6901). For `body` it points into the request body document, for example + // `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the + // parameter name, for example `/limit` or `/Idempotency-Key`. + Pointer string `json:"pointer"` + // Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or + // a value outside the schema). Clients must tolerate new values. + Code string `json:"code"` + // Fixed English message that never echoes the submitted value. + Message string `json:"message"` +} + +// GetIn returns the value of In. +func (s *ProblemFieldError) GetIn() ProblemFieldLocation { + return s.In +} + +// GetPointer returns the value of Pointer. +func (s *ProblemFieldError) GetPointer() string { + return s.Pointer +} + +// GetCode returns the value of Code. +func (s *ProblemFieldError) GetCode() string { + return s.Code +} + +// GetMessage returns the value of Message. +func (s *ProblemFieldError) GetMessage() string { + return s.Message +} + +// SetIn sets the value of In. +func (s *ProblemFieldError) SetIn(val ProblemFieldLocation) { + s.In = val +} + +// SetPointer sets the value of Pointer. +func (s *ProblemFieldError) SetPointer(val string) { + s.Pointer = val +} + +// SetCode sets the value of Code. +func (s *ProblemFieldError) SetCode(val string) { + s.Code = val +} + +// SetMessage sets the value of Message. +func (s *ProblemFieldError) SetMessage(val string) { + s.Message = val +} + +// Part of the request that contains the invalid field. +// Ref: #/components/schemas/ProblemFieldLocation +type ProblemFieldLocation string + +const ( + ProblemFieldLocationBody ProblemFieldLocation = "body" + ProblemFieldLocationQuery ProblemFieldLocation = "query" + ProblemFieldLocationPath ProblemFieldLocation = "path" + ProblemFieldLocationHeader ProblemFieldLocation = "header" + ProblemFieldLocationCookie ProblemFieldLocation = "cookie" +) + +// AllValues returns all ProblemFieldLocation values. +func (ProblemFieldLocation) AllValues() []ProblemFieldLocation { + return []ProblemFieldLocation{ + ProblemFieldLocationBody, + ProblemFieldLocationQuery, + ProblemFieldLocationPath, + ProblemFieldLocationHeader, + ProblemFieldLocationCookie, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProblemFieldLocation) MarshalText() ([]byte, error) { + switch s { + case ProblemFieldLocationBody: + return []byte(s), nil + case ProblemFieldLocationQuery: + return []byte(s), nil + case ProblemFieldLocationPath: + return []byte(s), nil + case ProblemFieldLocationHeader: + return []byte(s), nil + case ProblemFieldLocationCookie: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProblemFieldLocation) UnmarshalText(data []byte) error { + switch ProblemFieldLocation(data) { + case ProblemFieldLocationBody: + *s = ProblemFieldLocationBody + return nil + case ProblemFieldLocationQuery: + *s = ProblemFieldLocationQuery + return nil + case ProblemFieldLocationPath: + *s = ProblemFieldLocationPath + return nil + case ProblemFieldLocationHeader: + *s = ProblemFieldLocationHeader + return nil + case ProblemFieldLocationCookie: + *s = ProblemFieldLocationCookie + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// ProblemStatusCode wraps Problem with StatusCode. +type ProblemStatusCode struct { + StatusCode int + Response Problem +} + +// GetStatusCode returns the value of StatusCode. +func (s *ProblemStatusCode) GetStatusCode() int { + return s.StatusCode +} + +// GetResponse returns the value of Response. +func (s *ProblemStatusCode) GetResponse() Problem { + return s.Response +} + +// SetStatusCode sets the value of StatusCode. +func (s *ProblemStatusCode) SetStatusCode(val int) { + s.StatusCode = val +} + +// SetResponse sets the value of Response. +func (s *ProblemStatusCode) SetResponse(val Problem) { + s.Response = val +} diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index f6c5210..b3935a6 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -14,6 +14,10 @@ type Handler interface { // // GET /api/v1/healthz GetHealthz(ctx context.Context) (*HealthResponse, error) + // NewError creates *ProblemStatusCode from error returned by handler. + // + // Used for common default response. + NewError(ctx context.Context, err error) *ProblemStatusCode } // Server implements http server based on OpenAPI v3 specification and diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 2f510a3..590da62 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -21,3 +21,11 @@ var _ Handler = UnimplementedHandler{} func (UnimplementedHandler) GetHealthz(ctx context.Context) (r *HealthResponse, _ error) { return r, ht.ErrNotImplemented } + +// NewError creates *ProblemStatusCode from error returned by handler. +// +// Used for common default response. +func (UnimplementedHandler) NewError(ctx context.Context, err error) (r *ProblemStatusCode) { + r = new(ProblemStatusCode) + return r +} diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index 327111a..3081e2d 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -3,6 +3,8 @@ package api import ( + "fmt" + "github.com/go-faster/errors" "github.com/ogen-go/ogen/validate" ) @@ -38,3 +40,388 @@ func (s HealthResponseStatus) Validate() error { return errors.Errorf("invalid value: %v", s) } } + +func (s *Problem) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 256, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Type)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Title)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "title", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 400, + MaxSet: true, + Max: 599, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Status)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if err := s.Code.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Detail.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "detail", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Instance.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2048, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "instance", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TraceID.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "trace_id", + Error: err, + }) + } + if err := func() error { + if s.Errors == nil { + return nil // optional + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 100, + MaxLengthSet: true, + }).ValidateLength(len(s.Errors)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Errors { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "errors", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProblemCode) Validate() error { + switch s { + case "validation_failed": + return nil + case "unauthenticated": + return nil + case "forbidden": + return nil + case "not_found": + return nil + case "method_not_allowed": + return nil + case "idempotency_in_progress": + return nil + case "state_conflict": + return nil + case "version_conflict": + return nil + case "payload_too_large": + return nil + case "unsupported_media_type": + return nil + case "idempotency_key_reused": + return nil + case "precondition_required": + return nil + case "rate_limited": + return nil + case "internal": + return nil + case "not_implemented": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ProblemFieldError) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.In.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "in", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1024, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^(/([^~/]|~[01])*)*$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Pointer)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "pointer", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 64, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z][a-z0-9_]*$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Code)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 500, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Message)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "message", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProblemFieldLocation) Validate() error { + switch s { + case "body": + return nil + case "query": + return nil + case "path": + return nil + case "header": + return nil + case "cookie": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ProblemStatusCode) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} diff --git a/backend/internal/adapter/primary/http/problem/problem.go b/backend/internal/adapter/primary/http/problem/problem.go new file mode 100644 index 0000000..bb703c9 --- /dev/null +++ b/backend/internal/adapter/primary/http/problem/problem.go @@ -0,0 +1,142 @@ +// Package problem writes RFC 9457 problem details for the public HTTP API. +// +// Every public error body is an api.Problem with a stable api.ProblemCode. +// The status, title, and detail of each code are fixed here, so a response +// never carries internal error text or echoed request values. +package problem + +import ( + "context" + "net/http" + + kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware" + + "lincodex/backend/internal/adapter/primary/http/api" +) + +// MediaType is the RFC 9457 media type of every public error response. +const MediaType = "application/problem+json" + +// typePrefix forms the problem type URI; the contract documents this form. +const typePrefix = "urn:lincodex:problem:" + +type definition struct { + status int32 + title string + detail string +} + +var definitions = map[api.ProblemCode]definition{ + api.ProblemCodeValidationFailed: { + status: http.StatusBadRequest, + title: "Request validation failed", + detail: "One or more request fields are invalid.", + }, + api.ProblemCodeUnauthenticated: { + status: http.StatusUnauthorized, + title: "Authentication required", + detail: "Sign in and repeat the request.", + }, + api.ProblemCodeForbidden: { + status: http.StatusForbidden, + title: "Access denied", + detail: "You do not have permission to perform this operation.", + }, + api.ProblemCodeNotFound: { + status: http.StatusNotFound, + title: "Resource not found", + detail: "The requested resource does not exist.", + }, + api.ProblemCodeMethodNotAllowed: { + status: http.StatusMethodNotAllowed, + title: "Method not allowed", + detail: "The resource does not support this method; see the Allow header.", + }, + api.ProblemCodeIdempotencyInProgress: { + status: http.StatusConflict, + title: "Request with this idempotency key is in progress", + detail: "Retry after the original request completes.", + }, + api.ProblemCodeStateConflict: { + status: http.StatusConflict, + title: "Resource state conflict", + detail: "The resource is in a state that does not allow this operation.", + }, + api.ProblemCodeVersionConflict: { + status: http.StatusPreconditionFailed, + title: "Resource version conflict", + detail: "The resource changed after it was read. Read it again before retrying.", + }, + api.ProblemCodePayloadTooLarge: { + status: http.StatusRequestEntityTooLarge, + title: "Request body too large", + detail: "Reduce the request body size and retry.", + }, + api.ProblemCodeUnsupportedMediaType: { + status: http.StatusUnsupportedMediaType, + title: "Unsupported media type", + detail: "Send the request body with a media type that the operation accepts.", + }, + api.ProblemCodeIdempotencyKeyReused: { + status: http.StatusUnprocessableEntity, + title: "Idempotency key reused with a different request", + detail: "Use a new Idempotency-Key for a different request.", + }, + api.ProblemCodePreconditionRequired: { + status: http.StatusPreconditionRequired, + title: "Precondition required", + detail: "Send If-Match with the ETag of the version you read.", + }, + api.ProblemCodeRateLimited: { + status: http.StatusTooManyRequests, + title: "Too many requests", + detail: "Wait for the Retry-After interval and retry.", + }, + api.ProblemCodeInternal: { + status: http.StatusInternalServerError, + title: "Internal server error", + detail: "The server could not complete the request.", + }, + api.ProblemCodeNotImplemented: { + status: http.StatusNotImplemented, + title: "Operation not implemented", + detail: "This operation is not available yet.", + }, +} + +// New returns the problem response for code with its fixed status, title, +// and detail, and the request ID of ctx as trace_id. An unknown code yields +// the internal problem, so a caller cannot produce an undocumented status. +func New(ctx context.Context, code api.ProblemCode) *api.ProblemStatusCode { + known, ok := definitions[code] + if !ok { + code = api.ProblemCodeInternal + known = definitions[code] + } + response := api.Problem{ + Type: typePrefix + string(code), + Title: known.title, + Status: known.status, + Code: code, + Detail: api.NewOptString(known.detail), + } + if requestID := kitmiddleware.GetRequestID(ctx); requestID != "" { + response.TraceID = api.NewOptString(requestID) + } + return &api.ProblemStatusCode{StatusCode: int(known.status), Response: response} +} + +// Write sends problem as an application/problem+json response. +func Write(w http.ResponseWriter, problem *api.ProblemStatusCode) { + body, err := problem.Response.MarshalJSON() + if err != nil { + // The generated encoder does not fail for a Problem value; keep the + // status so the client still sees an error. + w.WriteHeader(problem.StatusCode) + return + } + w.Header().Set("Content-Type", MediaType) + w.WriteHeader(problem.StatusCode) + // The status is already committed; a failed write cannot be reported. + _, _ = w.Write(body) +} diff --git a/backend/internal/adapter/primary/http/problem/recover.go b/backend/internal/adapter/primary/http/problem/recover.go new file mode 100644 index 0000000..f6af8bf --- /dev/null +++ b/backend/internal/adapter/primary/http/problem/recover.go @@ -0,0 +1,98 @@ +package problem + +import ( + "bufio" + "errors" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "runtime/debug" + + "github.com/felixge/httpsnoop" + kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware" + + "lincodex/backend/internal/adapter/primary/http/api" +) + +// Recover answers a panic in next with the internal problem response and logs +// the panic type and stack once. It must run inside the request ID middleware so the problem +// and the log entry carry the request ID. When next has already started the +// response, the status is committed and no second body is written. A panic +// with http.ErrAbortHandler is re-raised so net/http aborts the response as +// that sentinel requires. +func (responder *Responder) Recover(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tracked, started := trackResponseStart(w) + defer responder.recoverPanic(w, r, started) + next.ServeHTTP(tracked, r) + }) +} + +// recoverPanic must be deferred directly so that recover stops the panic. +func (responder *Responder) recoverPanic(w http.ResponseWriter, r *http.Request, started *bool) { + recovered := recover() + if recovered == nil { + return + } + if err, ok := recovered.(error); ok && errors.Is(err, http.ErrAbortHandler) { + panic(recovered) + } + ctx := r.Context() + responder.logger.ErrorContext(ctx, "public API request panicked", + slog.String("request_id", kitmiddleware.GetRequestID(ctx)), + // The panic value may hold request data, so only its type is logged. + slog.String("panic_type", fmt.Sprintf("%T", recovered)), + slog.String("stack", string(debug.Stack())), + slog.Bool("response_started", *started), + ) + if !*started { + Write(w, New(ctx, api.ProblemCodeInternal)) + } +} + +// trackResponseStart wraps w, keeping its optional interfaces, and reports +// whether the handler has started the response. +func trackResponseStart(w http.ResponseWriter) (http.ResponseWriter, *bool) { + started := new(bool) + tracked := httpsnoop.Wrap(w, httpsnoop.Hooks{ + WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc { + return func(code int) { + *started = true + next(code) + } + }, + Write: func(next httpsnoop.WriteFunc) httpsnoop.WriteFunc { + return func(body []byte) (int, error) { + *started = true + return next(body) + } + }, + WriteString: func(next httpsnoop.WriteStringFunc) httpsnoop.WriteStringFunc { + return func(body string) (int, error) { + *started = true + return next(body) + } + }, + ReadFrom: func(next httpsnoop.ReadFromFunc) httpsnoop.ReadFromFunc { + return func(source io.Reader) (int64, error) { + *started = true + return next(source) + } + }, + Flush: func(next httpsnoop.FlushFunc) httpsnoop.FlushFunc { + return func() { + *started = true + next() + } + }, + Hijack: func(next httpsnoop.HijackFunc) httpsnoop.HijackFunc { + return func() (net.Conn, *bufio.ReadWriter, error) { + *started = true + return next() + } + }, + }) + return tracked, started +} diff --git a/backend/internal/adapter/primary/http/problem/recover_test.go b/backend/internal/adapter/primary/http/problem/recover_test.go new file mode 100644 index 0000000..a3be496 --- /dev/null +++ b/backend/internal/adapter/primary/http/problem/recover_test.go @@ -0,0 +1,66 @@ +package problem + +import ( + "bytes" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "lincodex/backend/internal/adapter/primary/http/api" +) + +func TestRecoverKeepsAStartedResponse(t *testing.T) { + var logs bytes.Buffer + responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil))) + handler := responder.Recover(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusAccepted) + _, _ = w.Write([]byte(`{"partial":`)) + panic("encoder failed") + })) + response := httptest.NewRecorder() + + handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/items", nil)) + + if response.Code != http.StatusAccepted || response.Body.String() != `{"partial":` { + t.Fatalf("response = %d %q, want the started response without a second body", response.Code, response.Body.String()) + } + if !strings.Contains(logs.String(), `"response_started":true`) { + t.Fatalf("panic was not logged with the started response: %s", logs.String()) + } +} + +func TestRecoverWritesInternalProblemBeforeTheResponseStarts(t *testing.T) { + var logs bytes.Buffer + responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil))) + handler := responder.Recover(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + panic("profile of jane@example.com") + })) + response := httptest.NewRecorder() + + handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/items", nil)) + + decodeProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal) + if strings.Contains(response.Body.String(), "jane") || strings.Contains(logs.String(), "jane") { + t.Fatalf("panic value leaked; body %s, logs %s", response.Body.String(), logs.String()) + } + if !strings.Contains(logs.String(), `"panic_type":"string"`) { + t.Fatalf("panic type was not logged: %s", logs.String()) + } +} + +func TestRecoverReraisesAbortHandler(t *testing.T) { + responder := NewResponder(slog.New(slog.DiscardHandler)) + handler := responder.Recover(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + panic(http.ErrAbortHandler) + })) + defer func() { + if recovered := recover(); recovered != http.ErrAbortHandler { //nolint:errorlint // net/http compares the sentinel by identity + t.Fatalf("recovered %v, want http.ErrAbortHandler", recovered) + } + }() + + handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/v1/items", nil)) + t.Fatal("ServeHTTP returned instead of re-raising http.ErrAbortHandler") +} diff --git a/backend/internal/adapter/primary/http/problem/responder.go b/backend/internal/adapter/primary/http/problem/responder.go new file mode 100644 index 0000000..148b98f --- /dev/null +++ b/backend/internal/adapter/primary/http/problem/responder.go @@ -0,0 +1,240 @@ +package problem + +import ( + "context" + "errors" + "log/slog" + "net/http" + "regexp" + "strings" + + ht "github.com/ogen-go/ogen/http" + "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/openapi" + "github.com/ogen-go/ogen/validate" + kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware" + + "lincodex/backend/internal/adapter/primary/http/api" +) + +// Field reasons published in ProblemFieldError.code. +const ( + fieldCodeRequired = "required" + fieldCodeInvalid = "invalid" +) + +const ( + fieldMessageRequired = "The value is required." + fieldMessageInvalid = "The value does not match the contract." + // maxFieldErrors matches the maxItems bound of Problem.errors. + maxFieldErrors = 100 + // wholeBodyPointer is the JSON Pointer of the request body root. + wholeBodyPointer = "" +) + +// arrayIndexName matches the "[index]" names that generated validators use +// for array items. +var arrayIndexName = regexp.MustCompile(`^\[(\d+)\]$`) + +var pointerTokenEscaper = strings.NewReplacer("~", "~0", "/", "~1") + +var parameterLocations = map[openapi.ParameterLocation]api.ProblemFieldLocation{ + openapi.LocationQuery: api.ProblemFieldLocationQuery, + openapi.LocationHeader: api.ProblemFieldLocationHeader, + openapi.LocationPath: api.ProblemFieldLocationPath, + openapi.LocationCookie: api.ProblemFieldLocationCookie, +} + +// Responder maps errors at the public HTTP boundary to problem responses and +// logs the errors that are not the client's fault. It logs the error text of +// internal failures, so handwritten errors must follow the backend error +// standard and never carry personal data, request bodies, credentials, or +// other secrets. A request canceled by its client is logged at info level +// because it is not a server failure. +type Responder struct { + logger *slog.Logger +} + +func NewResponder(logger *slog.Logger) *Responder { + return &Responder{logger: logger} +} + +// HandlerError builds the response for an error returned by an api.Handler +// operation; it implements the contract of api.Handler.NewError. The +// generated server passes security failures here as well, so a +// *ogenerrors.SecurityError becomes 401. Authorization decisions that need 403 +// return a typed *api.ProblemStatusCode from the operation instead, which the +// generated server encodes without calling NewError. +func (responder *Responder) HandlerError(ctx context.Context, err error) *api.ProblemStatusCode { + if _, ok := errors.AsType[*ogenerrors.SecurityError](err); ok { + return New(ctx, api.ProblemCodeUnauthenticated) + } + responder.logInternal(ctx, err) + return New(ctx, api.ProblemCodeInternal) +} + +// HandleServerError is the ErrorHandler of the generated server. It receives +// ht.ErrNotImplemented, request decoding and validation errors, and response +// encoding failures. +func (responder *Responder) HandleServerError(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) { + Write(w, responder.serverErrorProblem(ctx, r, err)) +} + +// NotFound answers a path that matches no operation of the generated server. +func (*Responder) NotFound(w http.ResponseWriter, r *http.Request) { + Write(w, New(r.Context(), api.ProblemCodeNotFound)) +} + +// MethodNotAllowed answers a known path requested with an unsupported method. +// The generated server has already set Access-Control-Allow-Methods for a +// CORS preflight, which keeps its empty 204 response. +func (*Responder) MethodNotAllowed(w http.ResponseWriter, r *http.Request, allowed string) { + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusNoContent) + return + } + w.Header().Set("Allow", allowed) + Write(w, New(r.Context(), api.ProblemCodeMethodNotAllowed)) +} + +func (responder *Responder) serverErrorProblem(ctx context.Context, r *http.Request, err error) *api.ProblemStatusCode { + if errors.Is(err, ht.ErrNotImplemented) { + return New(ctx, api.ProblemCodeNotImplemented) + } + // A body limit set with http.MaxBytesReader surfaces inside the decoding + // error, so it is checked before the generic request decoding branch. + if _, ok := errors.AsType[*http.MaxBytesError](err); ok { + return New(ctx, api.ProblemCodePayloadTooLarge) + } + if _, ok := errors.AsType[*validate.InvalidContentTypeError](err); ok { + return New(ctx, api.ProblemCodeUnsupportedMediaType) + } + if _, ok := errors.AsType[*ogenerrors.SecurityError](err); ok { + return New(ctx, api.ProblemCodeUnauthenticated) + } + if paramsErr, ok := errors.AsType[*ogenerrors.DecodeParamsError](err); ok { + return validationProblem(ctx, parameterFieldErrors(r, paramsErr)) + } + if requestErr, ok := errors.AsType[*ogenerrors.DecodeRequestError](err); ok { + return validationProblem(ctx, bodyFieldErrors(requestErr)) + } + responder.logInternal(ctx, err) + return New(ctx, api.ProblemCodeInternal) +} + +func (responder *Responder) logInternal(ctx context.Context, err error) { + if errors.Is(err, context.Canceled) { + responder.logger.InfoContext(ctx, "public API request canceled by client", + slog.String("request_id", kitmiddleware.GetRequestID(ctx)), + ) + return + } + responder.logger.ErrorContext(ctx, "public API request failed", + slog.String("request_id", kitmiddleware.GetRequestID(ctx)), + slog.String("error", err.Error()), + ) +} + +func validationProblem(ctx context.Context, fields []api.ProblemFieldError) *api.ProblemStatusCode { + problem := New(ctx, api.ProblemCodeValidationFailed) + problem.Response.Errors = fields + return problem +} + +func parameterFieldErrors(r *http.Request, err error) []api.ProblemFieldError { + paramErr, ok := errors.AsType[*ogenerrors.DecodeParamError](err) + if !ok { + return nil + } + location, ok := parameterLocations[paramErr.In] + if !ok { + return nil + } + code := fieldCodeInvalid + if errors.Is(paramErr.Err, validate.ErrFieldRequired) || !parameterPresent(r, paramErr.In, paramErr.Name) { + code = fieldCodeRequired + } + return []api.ProblemFieldError{fieldError(location, "/"+escapePointerToken(paramErr.Name), code)} +} + +// parameterPresent reports whether the request carries the parameter. The +// generated decoder reports a missing query parameter with a plain error, so +// presence is checked on the request instead of in the error text. +func parameterPresent(r *http.Request, in openapi.ParameterLocation, name string) bool { + switch in { + case openapi.LocationQuery: + return r.URL.Query().Has(name) + case openapi.LocationHeader: + return len(r.Header.Values(name)) > 0 + case openapi.LocationCookie: + _, err := r.Cookie(name) + return err == nil + case openapi.LocationPath: + // A request without the path segment matches no route. + return true + default: + return true + } +} + +func bodyFieldErrors(err error) []api.ProblemFieldError { + if errors.Is(err, validate.ErrBodyRequired) { + return []api.ProblemFieldError{fieldError(api.ProblemFieldLocationBody, wholeBodyPointer, fieldCodeRequired)} + } + + var fields []api.ProblemFieldError + if decodeErr, ok := errors.AsType[*ogenerrors.DecodeBodyError](err); ok { + // Only a validation error that is the direct decoding cause names + // top-level fields. A wrapped one comes from a nested object whose + // path the decoder does not record, so it maps to the whole body. + if topLevel, ok := decodeErr.Err.(*validate.Error); ok { //nolint:errorlint // the unwrapped cause alone identifies top-level fields + fields = appendSchemaFieldErrors(fields, topLevel, wholeBodyPointer) + } + } else if validationErr, ok := errors.AsType[*validate.Error](err); ok { + // Schema validation after decoding nests field errors by path. + fields = appendSchemaFieldErrors(fields, validationErr, wholeBodyPointer) + } + if len(fields) == 0 { + return []api.ProblemFieldError{fieldError(api.ProblemFieldLocationBody, wholeBodyPointer, fieldCodeInvalid)} + } + return fields +} + +func appendSchemaFieldErrors(fields []api.ProblemFieldError, err *validate.Error, prefix string) []api.ProblemFieldError { + for _, field := range err.Fields { + if len(fields) >= maxFieldErrors { + return fields + } + pointer := prefix + "/" + pointerToken(field.Name) + if nested, ok := field.Error.(*validate.Error); ok { //nolint:errorlint // only a direct nested validation error carries child paths + fields = appendSchemaFieldErrors(fields, nested, pointer) + continue + } + code := fieldCodeInvalid + if errors.Is(field.Error, validate.ErrFieldRequired) { + code = fieldCodeRequired + } + fields = append(fields, fieldError(api.ProblemFieldLocationBody, pointer, code)) + } + return fields +} + +func pointerToken(name string) string { + if match := arrayIndexName.FindStringSubmatch(name); match != nil { + return match[1] + } + return escapePointerToken(name) +} + +// escapePointerToken escapes a reference token as RFC 6901 requires. +func escapePointerToken(token string) string { + return pointerTokenEscaper.Replace(token) +} + +func fieldError(location api.ProblemFieldLocation, pointer, code string) api.ProblemFieldError { + message := fieldMessageInvalid + if code == fieldCodeRequired { + message = fieldMessageRequired + } + return api.ProblemFieldError{In: location, Pointer: pointer, Code: code, Message: message} +} diff --git a/backend/internal/adapter/primary/http/problem/responder_test.go b/backend/internal/adapter/primary/http/problem/responder_test.go new file mode 100644 index 0000000..47b8d7d --- /dev/null +++ b/backend/internal/adapter/primary/http/problem/responder_test.go @@ -0,0 +1,261 @@ +package problem + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "strings" + "testing" + + ht "github.com/ogen-go/ogen/http" + "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/openapi" + "github.com/ogen-go/ogen/uri" + "github.com/ogen-go/ogen/validate" + + "lincodex/backend/internal/adapter/primary/http/api" +) + +// The errors below are built the way the generated server builds them, so the +// tests cover the mapping for decoder paths that the current public contract +// has no input for. The compatibility fixture exercises the same mapping +// through a real generated server in make -C backend check-ogen-compat. +func TestHandleServerErrorMapsGeneratedErrors(t *testing.T) { + operation := ogenerrors.OperationContext{Name: "CreateItem", ID: "CreateItem"} + for _, test := range []struct { + name string + request *http.Request + err error + statusCode int + code api.ProblemCode + fields []api.ProblemFieldError + }{ + { + name: "not implemented", + request: httptest.NewRequest(http.MethodGet, "/api/v1/items", nil), + err: ht.ErrNotImplemented, + statusCode: http.StatusNotImplemented, + code: api.ProblemCodeNotImplemented, + }, + { + name: "missing query parameter", + request: httptest.NewRequest(http.MethodGet, "/api/v1/items", nil), + err: &ogenerrors.DecodeParamsError{OperationContext: operation, Err: &ogenerrors.DecodeParamError{ + Name: "state", In: openapi.LocationQuery, Err: missingQueryParameter("state"), + }}, + statusCode: http.StatusBadRequest, + code: api.ProblemCodeValidationFailed, + fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationQuery, Pointer: "/state", Code: "required", Message: fieldMessageRequired}}, + }, + { + name: "invalid query parameter", + request: httptest.NewRequest(http.MethodGet, "/api/v1/items?limit=1000", nil), + err: &ogenerrors.DecodeParamsError{OperationContext: operation, Err: &ogenerrors.DecodeParamError{ + Name: "limit", In: openapi.LocationQuery, + Err: fmt.Errorf("int: %w", validate.Int{MinSet: true, Min: 1, MaxSet: true, Max: 100}.Validate(1000)), + }}, + statusCode: http.StatusBadRequest, + code: api.ProblemCodeValidationFailed, + fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationQuery, Pointer: "/limit", Code: "invalid", Message: fieldMessageInvalid}}, + }, + { + name: "missing header", + request: httptest.NewRequest(http.MethodPost, "/api/v1/items", nil), + err: &ogenerrors.DecodeParamsError{OperationContext: operation, Err: &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", In: openapi.LocationHeader, + Err: &validate.Error{Fields: []validate.FieldError{{Name: "Idempotency-Key", Error: validate.ErrFieldRequired}}}, + }}, + statusCode: http.StatusBadRequest, + code: api.ProblemCodeValidationFailed, + fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationHeader, Pointer: "/Idempotency-Key", Code: "required", Message: fieldMessageRequired}}, + }, + { + name: "missing body", + request: httptest.NewRequest(http.MethodPost, "/api/v1/items", nil), + err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: validate.ErrBodyRequired}, + statusCode: http.StatusBadRequest, + code: api.ProblemCodeValidationFailed, + fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "", Code: "required", Message: fieldMessageRequired}}, + }, + { + name: "missing top-level body field", + request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)), + err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: &ogenerrors.DecodeBodyError{ + ContentType: "application/json", Body: []byte(`{}`), + Err: &validate.Error{Fields: []validate.FieldError{{Name: "name", Error: validate.ErrFieldRequired}}}, + }}, + statusCode: http.StatusBadRequest, + code: api.ProblemCodeValidationFailed, + fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/name", Code: "required", Message: fieldMessageRequired}}, + }, + { + name: "nested decoding failure has no reliable path", + request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{"page":{}}`)), + err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: &ogenerrors.DecodeBodyError{ + ContentType: "application/json", Body: []byte(`{"page":{}}`), + Err: fmt.Errorf("decode field \"page\": %w", &validate.Error{Fields: []validate.FieldError{{Name: "has_more", Error: validate.ErrFieldRequired}}}), + }}, + statusCode: http.StatusBadRequest, + code: api.ProblemCodeValidationFailed, + fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "", Code: "invalid", Message: fieldMessageInvalid}}, + }, + { + name: "schema validation keeps nested paths", + request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)), + err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: fmt.Errorf("validate: %w", &validate.Error{Fields: []validate.FieldError{ + {Name: "items", Error: &validate.Error{Fields: []validate.FieldError{ + {Name: "[2]", Error: &validate.Error{Fields: []validate.FieldError{{Name: "a/b", Error: &validate.MaxLengthError{Len: 101, MaxLength: 100}}}}}, + }}}, + }})}, + statusCode: http.StatusBadRequest, + code: api.ProblemCodeValidationFailed, + fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/items/2/a~1b", Code: "invalid", Message: fieldMessageInvalid}}, + }, + { + name: "body over the size limit", + request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{"name":"probe"}`)), + err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: readOverLimit(t)}, + statusCode: http.StatusRequestEntityTooLarge, + code: api.ProblemCodePayloadTooLarge, + }, + { + name: "unsupported media type", + request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`name`)), + err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: validate.InvalidContentType("text/plain")}, + statusCode: http.StatusUnsupportedMediaType, + code: api.ProblemCodeUnsupportedMediaType, + }, + { + name: "security failure", + request: httptest.NewRequest(http.MethodGet, "/api/v1/items", nil), + err: &ogenerrors.SecurityError{OperationContext: operation, Security: "cookieAuth", Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied}, + statusCode: http.StatusUnauthorized, + code: api.ProblemCodeUnauthenticated, + }, + } { + t.Run(test.name, func(t *testing.T) { + var logs bytes.Buffer + responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil))) + response := httptest.NewRecorder() + + responder.HandleServerError(test.request.Context(), response, test.request, test.err) + + body := decodeProblem(t, response, test.statusCode, test.code) + if !reflect.DeepEqual(body.Errors, test.fields) { + t.Fatalf("errors = %+v, want %+v", body.Errors, test.fields) + } + if logs.Len() != 0 { + t.Fatalf("a client error was logged as a server failure: %s", logs.String()) + } + }) + } +} + +func TestHandleServerErrorHidesAndLogsUnexpectedErrors(t *testing.T) { + const internalText = "encode response: write failed" + var logs bytes.Buffer + responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil))) + request := httptest.NewRequest(http.MethodGet, "/api/v1/items", nil) + response := httptest.NewRecorder() + + responder.HandleServerError(request.Context(), response, request, errors.New(internalText)) + + decodeProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal) + if strings.Contains(response.Body.String(), "write failed") { + t.Fatalf("response exposes internal error text: %s", response.Body.String()) + } + if !strings.Contains(logs.String(), internalText) || !strings.Contains(logs.String(), `"level":"ERROR"`) { + t.Fatalf("unexpected error was not logged as an error: %s", logs.String()) + } +} + +func TestClientCancellationIsNotLoggedAsServerFailure(t *testing.T) { + var logs bytes.Buffer + responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil))) + + got := responder.HandlerError(context.Background(), fmt.Errorf("HealthHandler.GetHealthz - query: %w", context.Canceled)) + + if got.StatusCode != http.StatusInternalServerError || got.Response.Code != api.ProblemCodeInternal { + t.Fatalf("canceled request = %d %q, want 500 internal", got.StatusCode, got.Response.Code) + } + if strings.Contains(logs.String(), `"level":"ERROR"`) || !strings.Contains(logs.String(), "canceled by client") { + t.Fatalf("client cancellation was not logged at info level: %s", logs.String()) + } +} + +func TestHandlerErrorSeparatesSecurityFailures(t *testing.T) { + responder := NewResponder(slog.New(slog.DiscardHandler)) + securityErr := &ogenerrors.SecurityError{Security: "cookieAuth", Err: errors.New("session expired")} + + if got := responder.HandlerError(context.Background(), securityErr); got.StatusCode != http.StatusUnauthorized || got.Response.Code != api.ProblemCodeUnauthenticated { + t.Fatalf("security failure = %d %q, want 401 unauthenticated", got.StatusCode, got.Response.Code) + } + if got := responder.HandlerError(context.Background(), errors.New("query failed")); got.StatusCode != http.StatusInternalServerError || got.Response.Code != api.ProblemCodeInternal { + t.Fatalf("internal failure = %d %q, want 500 internal", got.StatusCode, got.Response.Code) + } +} + +func TestNewFallsBackToInternalForUnknownCode(t *testing.T) { + got := New(context.Background(), api.ProblemCode("undocumented")) + if got.StatusCode != http.StatusInternalServerError || got.Response.Code != api.ProblemCodeInternal { + t.Fatalf("unknown code = %d %q, want 500 internal", got.StatusCode, got.Response.Code) + } +} + +func TestEveryContractCodeHasAnErrorStatus(t *testing.T) { + for _, code := range api.ProblemCodeInternal.AllValues() { + got := New(context.Background(), code) + if got.Response.Code != code { + t.Errorf("code %q has no definition and falls back to %q", code, got.Response.Code) + } + if err := got.Response.Validate(); err != nil { + t.Errorf("code %q builds an invalid problem: %v", code, err) + } + } +} + +func decodeProblem(t *testing.T, response *httptest.ResponseRecorder, statusCode int, code api.ProblemCode) api.Problem { + t.Helper() + if response.Code != statusCode { + t.Fatalf("status code = %d, want %d: %s", response.Code, statusCode, response.Body.String()) + } + if contentType := response.Header().Get("Content-Type"); contentType != MediaType { + t.Fatalf("Content-Type = %q, want %q", contentType, MediaType) + } + var body api.Problem + if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil { + t.Fatalf("decode problem %s: %v", response.Body.String(), err) + } + if err := body.Validate(); err != nil { + t.Fatalf("problem %s violates the contract: %v", response.Body.String(), err) + } + if body.Code != code { + t.Fatalf("code = %q, want %q", body.Code, code) + } + return body +} + +func missingQueryParameter(name string) error { + return uri.NewQueryDecoder(url.Values{}).HasParam(uri.QueryParameterDecodingConfig{ + Name: name, Style: uri.QueryStyleForm, Explode: true, + }) +} + +// readOverLimit returns the error that http.MaxBytesReader produces, as the +// generated request decoder would receive it. +func readOverLimit(t *testing.T) error { + t.Helper() + body := http.MaxBytesReader(httptest.NewRecorder(), io.NopCloser(strings.NewReader(`{"name":"probe"}`)), 4) + _, err := io.ReadAll(body) + if err == nil { + t.Fatal("MaxBytesReader accepted a body over its limit") + } + return err +} diff --git a/backend/internal/adapter/primary/http/router.go b/backend/internal/adapter/primary/http/router.go index 2079aea..056ac6c 100644 --- a/backend/internal/adapter/primary/http/router.go +++ b/backend/internal/adapter/primary/http/router.go @@ -10,36 +10,62 @@ import ( apiadapter "lincodex/backend/internal/adapter/primary/http/api" httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware" + "lincodex/backend/internal/adapter/primary/http/problem" v1 "lincodex/backend/internal/adapter/primary/http/v1" ) const ( healthPath = "/healthz" readinessPath = "/readyz" + apiRoot = "/api" + publicPrefix = apiRoot + "/v1" ) // NewRouter mounts the internal operational routes and the generated public API. -// The generated server keeps ogen's default error handler, which answers -// ht.ErrNotImplemented with HTTP 501; operations without a business -// implementation in apiHandler rely on that mapping. +// Every error under /api/v1 is an RFC 9457 problem response: problems maps +// ht.ErrNotImplemented to 501, request decoding and validation errors to 400, +// unknown routes under /api to 404, unsupported methods to 405, and any other +// server error or panic to 500 without exposing its text. Operation errors go +// through apiHandler.NewError. func NewRouter( health *v1.HealthHandler, apiHandler apiadapter.Handler, + problems *problem.Responder, collector httpmiddleware.RequestMetrics, logger *slog.Logger, ) (http.Handler, error) { - apiServer, err := apiadapter.NewServer(apiHandler) + apiServer, err := apiadapter.NewServer( + apiHandler, + apiadapter.WithErrorHandler(problems.HandleServerError), + apiadapter.WithNotFound(problems.NotFound), + apiadapter.WithMethodNotAllowed(problems.MethodNotAllowed), + ) if err != nil { return nil, fmt.Errorf("httpadapter.NewRouter - create API server: %w", err) } router := chi.NewRouter() + // Request ID, request logging, and metrics wrap every route, so both + // recovery middlewares below run inside them: a recovered panic carries the + // request ID and its 500 is logged and counted. router.Use(kitmiddleware.RequestID()) - router.Use(kitmiddleware.Recoverer(logger)) router.Use(kitmiddleware.Logger(logger, nil, kitmiddleware.WithSkipPaths(healthPath, readinessPath))) router.Use(httpmiddleware.CollectMetrics(collector)) - router.Get(healthPath, health.Healthz) - router.Get(readinessPath, health.Readyz) - router.Handle("/api/v1/*", apiServer) + router.Group(func(operational chi.Router) { + operational.Use(kitmiddleware.Recoverer(logger)) + operational.Get(healthPath, health.Healthz) + operational.Get(readinessPath, health.Readyz) + }) + // The public API uses only problems.Recover, which answers panics with the + // contract's internal problem and re-raises http.ErrAbortHandler so the + // server aborts the response; the kit Recoverer would swallow that panic. + router.Group(func(public chi.Router) { + public.Use(problems.Recover) + public.Handle(publicPrefix+"/*", apiServer) + // Unknown /api paths outside the versioned prefix are also problems, + // so every error under /api has the contract's format. + public.Handle(apiRoot, http.HandlerFunc(problems.NotFound)) + public.Handle(apiRoot+"/*", http.HandlerFunc(problems.NotFound)) + }) return router, nil } diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index 7f11990..925a945 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -1,26 +1,47 @@ package httpadapter import ( + "bytes" "context" "encoding/json" + "errors" + "fmt" "log/slog" "net/http" "net/http/httptest" + "strings" "testing" "time" "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" v1 "lincodex/backend/internal/adapter/primary/http/v1" metrics "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/usecase/health" ) +// internalFailureText stands for internal error text that must stay in logs. +const internalFailureText = "dial tcp 10.0.0.5:5432: connection refused" + type readinessFunc func(context.Context) error func (check readinessFunc) Check(ctx context.Context) error { return check(ctx) } +// healthzOverride replaces GetHealthz of the production composite handler, +// keeping its NewError, so a test can drive operation error handling without +// adding operations to the public contract. +type healthzOverride struct { + *v1.Handler + + getHealthz func(context.Context) (*api.HealthResponse, error) +} + +func (handler healthzOverride) GetHealthz(ctx context.Context) (*api.HealthResponse, error) { + return handler.getHealthz(ctx) +} + func TestOperationalHealthRoutes(t *testing.T) { for _, test := range []struct { name string @@ -60,14 +81,12 @@ func TestPublicHealthRouteUsesGeneratedOgenHandler(t *testing.T) { if response.Code != http.StatusOK { t.Fatalf("status code = %d, want %d: %s", response.Code, http.StatusOK, response.Body.String()) } - var body struct { - Status string `json:"status"` + var body api.HealthResponse + if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil { + t.Fatalf("decode response %s: %v", response.Body.String(), err) } - if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { - t.Fatalf("decode response: %v", err) - } - if body.Status != "ok" { - t.Fatalf("status = %q, want %q", body.Status, "ok") + if body.Status != api.HealthResponseStatusOk { + t.Fatalf("status = %q, want %q", body.Status, api.HealthResponseStatusOk) } } @@ -75,29 +94,256 @@ func TestPublicHealthRouteUsesGeneratedOgenHandler(t *testing.T) { // router instead of a successful stub or a generic 500. GetHealthz served by // api.UnimplementedHandler stands in for any such operation, so the check needs // no extra contract operation. -func TestPublicUnimplementedOperationReturnsNotImplemented(t *testing.T) { +func TestPublicUnimplementedOperationReturnsNotImplementedProblem(t *testing.T) { healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) - router := newTestRouterWithAPI(t, healthHandler, api.UnimplementedHandler{}) + router := newTestRouterWithAPI(t, healthHandler, api.UnimplementedHandler{}, slog.New(slog.DiscardHandler)) response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) - if response.Code != http.StatusNotImplemented { - t.Fatalf("status code = %d, want %d: %s", response.Code, http.StatusNotImplemented, response.Body.String()) + + body := requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented) + if body.Errors != nil { + t.Fatalf("errors = %v, want none", body.Errors) } } +func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) { + var logs bytes.Buffer + logger := slog.New(slog.NewJSONHandler(&logs, nil)) + router := newOverrideRouter(t, logger, func(context.Context) (*api.HealthResponse, error) { + return nil, fmt.Errorf("HealthHandler.GetHealthz - check database: %w", errors.New(internalFailureText)) + }) + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) + + body := requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal) + if body.Title != "Internal server error" { + t.Fatalf("title = %q, want the fixed internal title", body.Title) + } + if strings.Contains(response.Body.String(), "connection refused") || strings.Contains(response.Body.String(), "HealthHandler") { + t.Fatalf("response exposes internal error text: %s", response.Body.String()) + } + if !strings.Contains(logs.String(), internalFailureText) { + t.Fatalf("internal error was not logged at the HTTP boundary: %s", logs.String()) + } + if requestID := response.Header().Get("X-Request-ID"); !strings.Contains(logs.String(), requestID) { + t.Fatalf("log entry has no request ID %q: %s", requestID, logs.String()) + } +} + +// recordedRequest is one observation passed to the metrics middleware. +type recordedRequest struct { + route string + status int +} + +type requestRecorder struct { + requests []recordedRequest +} + +func (recorder *requestRecorder) ObserveRequest(_, route string, status int, _ time.Duration) { + recorder.requests = append(recorder.requests, recordedRequest{route: route, status: status}) +} + +func TestPublicOperationPanicReturnsInternalProblem(t *testing.T) { + const panicText = "nil map write for candidate jane@example.com" + var logs bytes.Buffer + logger := slog.New(slog.NewJSONHandler(&logs, nil)) + healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) + handler := healthzOverride{ + Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), + getHealthz: func(context.Context) (*api.HealthResponse, error) { panic(panicText) }, + } + recorder := &requestRecorder{} + router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), recorder, logger) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) + + body := requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal) + if body.Title != "Internal server error" { + t.Fatalf("title = %q, want the fixed internal title", body.Title) + } + if strings.Contains(response.Body.String(), "jane") || strings.Contains(response.Body.String(), "nil map") { + t.Fatalf("response exposes the panic: %s", response.Body.String()) + } + if count := strings.Count(logs.String(), "public API request panicked"); count != 1 { + t.Fatalf("panic logged %d times, want once: %s", count, logs.String()) + } + if !strings.Contains(logs.String(), response.Header().Get("X-Request-ID")) { + t.Fatalf("panic log has no request ID: %s", logs.String()) + } + if strings.Contains(logs.String(), "jane@example.com") { + t.Fatalf("panic value with personal data reached the logs: %s", logs.String()) + } + want := []recordedRequest{{route: "/api/v1/*", status: http.StatusInternalServerError}} + if fmt.Sprint(recorder.requests) != fmt.Sprint(want) { + t.Fatalf("metrics observed %v, want %v", recorder.requests, want) + } +} + +// http.ErrAbortHandler must reach net/http, which then aborts the response +// instead of sending a problem or a success. +func TestPublicOperationAbortPropagatesToTheServer(t *testing.T) { + recorder := &requestRecorder{} + router := newOverrideRouterWithMetrics(t, recorder, func(context.Context) (*api.HealthResponse, error) { + panic(http.ErrAbortHandler) + }) + + func() { + defer func() { + if recovered := recover(); recovered != http.ErrAbortHandler { //nolint:errorlint // net/http compares the sentinel by identity + t.Fatalf("recovered %v, want http.ErrAbortHandler", recovered) + } + }() + router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) + t.Fatal("ServeHTTP returned instead of re-raising http.ErrAbortHandler") + }() + + server := httptest.NewServer(router) + defer server.Close() + request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL+"/api/v1/healthz", nil) + if err != nil { + t.Fatalf("build request: %v", err) + } + response, err := server.Client().Do(request) + if err == nil { + _ = response.Body.Close() + t.Fatalf("server answered %d, want an aborted connection", response.StatusCode) + } +} + +func TestUnknownAPIPathsOutsideTheVersionReturnNotFoundProblem(t *testing.T) { + router := newTestRouter(t, func(context.Context) error { return nil }) + for _, path := range []string{"/api", "/api/", "/api/v2/healthz", "/api/v1"} { + t.Run(path, func(t *testing.T) { + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil)) + + requireProblem(t, response, http.StatusNotFound, api.ProblemCodeNotFound) + }) + } +} + +// Operations report expected failures as typed problems, which the generated +// server encodes directly with their own status. +func TestPublicOperationTypedProblemKeepsItsStatus(t *testing.T) { + for _, test := range []struct { + name string + code api.ProblemCode + statusCode int + }{ + {name: "forbidden", code: api.ProblemCodeForbidden, statusCode: http.StatusForbidden}, + {name: "version conflict", code: api.ProblemCodeVersionConflict, statusCode: http.StatusPreconditionFailed}, + } { + t.Run(test.name, func(t *testing.T) { + router := newOverrideRouter(t, slog.New(slog.DiscardHandler), func(ctx context.Context) (*api.HealthResponse, error) { + return nil, problem.New(ctx, test.code) + }) + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) + + requireProblem(t, response, test.statusCode, test.code) + }) + } +} + +func TestPublicUnknownRouteReturnsNotFoundProblem(t *testing.T) { + router := newTestRouter(t, func(context.Context) error { return nil }) + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/missing", nil)) + + requireProblem(t, response, http.StatusNotFound, api.ProblemCodeNotFound) +} + +func TestPublicUnsupportedMethodReturnsMethodNotAllowedProblem(t *testing.T) { + router := newTestRouter(t, func(context.Context) error { return nil }) + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/api/v1/healthz", nil)) + + requireProblem(t, response, http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed) + if allowed := response.Header().Get("Allow"); allowed != http.MethodGet { + t.Fatalf("Allow = %q, want %q", allowed, http.MethodGet) + } +} + +func TestPublicPreflightKeepsEmptyResponse(t *testing.T) { + router := newTestRouter(t, func(context.Context) error { return nil }) + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodOptions, "/api/v1/healthz", nil)) + + if response.Code != http.StatusNoContent || response.Body.Len() != 0 { + t.Fatalf("preflight = %d %q, want empty 204", response.Code, response.Body.String()) + } + if methods := response.Header().Get("Access-Control-Allow-Methods"); methods != http.MethodGet { + t.Fatalf("Access-Control-Allow-Methods = %q, want %q", methods, http.MethodGet) + } +} + +// requireProblem checks the problem+json envelope and returns the body decoded +// and validated by the generated contract types. +func requireProblem(t *testing.T, response *httptest.ResponseRecorder, statusCode int, code api.ProblemCode) api.Problem { + t.Helper() + if response.Code != statusCode { + t.Fatalf("status code = %d, want %d: %s", response.Code, statusCode, response.Body.String()) + } + if contentType := response.Header().Get("Content-Type"); contentType != problem.MediaType { + t.Fatalf("Content-Type = %q, want %q", contentType, problem.MediaType) + } + var body api.Problem + if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil { + t.Fatalf("decode problem %s: %v", response.Body.String(), err) + } + if err := body.Validate(); err != nil { + t.Fatalf("problem %s violates the contract: %v", response.Body.String(), err) + } + if body.Code != code || int(body.Status) != statusCode { + t.Fatalf("problem code/status = %q/%d, want %q/%d", body.Code, body.Status, code, statusCode) + } + if body.Type != "urn:lincodex:problem:"+string(code) { + t.Fatalf("problem type = %q", body.Type) + } + traceID, ok := body.TraceID.Get() + if !ok || traceID != response.Header().Get("X-Request-ID") { + t.Fatalf("trace_id = %q, want the X-Request-ID header %q", traceID, response.Header().Get("X-Request-ID")) + } + return body +} + func newTestRouter(t *testing.T, checker readinessFunc) http.Handler { t.Helper() + logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(checker) - return newTestRouterWithAPI(t, healthHandler, v1.NewHandler(healthHandler)) + return newTestRouterWithAPI(t, healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), logger) +} + +func newOverrideRouter(t *testing.T, logger *slog.Logger, getHealthz func(context.Context) (*api.HealthResponse, error)) http.Handler { + t.Helper() + healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) + handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz} + return newTestRouterWithAPI(t, healthHandler, handler, logger) } func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler { return v1.NewHealthHandler(health.NewReadiness(checker), time.Second) } -func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler) http.Handler { +func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler, logger *slog.Logger) http.Handler { t.Helper() - router, err := NewRouter(healthHandler, apiHandler, metrics.New(), slog.New(slog.DiscardHandler)) + router, err := NewRouter(healthHandler, apiHandler, problem.NewResponder(logger), metrics.New(), logger) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return router +} + +func newOverrideRouterWithMetrics(t *testing.T, collector *requestRecorder, getHealthz func(context.Context) (*api.HealthResponse, error)) http.Handler { + t.Helper() + logger := slog.New(slog.DiscardHandler) + healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) + handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz} + router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), collector, logger) if err != nil { t.Fatalf("NewRouter() error = %v", err) } diff --git a/backend/internal/adapter/primary/http/v1/handler.go b/backend/internal/adapter/primary/http/v1/handler.go index d40933d..ef70749 100644 --- a/backend/internal/adapter/primary/http/v1/handler.go +++ b/backend/internal/adapter/primary/http/v1/handler.go @@ -4,6 +4,7 @@ import ( "context" "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" ) // Handler is the composite implementation of the generated api.Handler. @@ -11,17 +12,17 @@ import ( // The embedded api.UnimplementedHandler keeps the backend compiling after the // contract gains an operation that has no business implementation yet. Such an // operation returns ht.ErrNotImplemented without side effects. The generated -// server passes that error to its configured ErrorHandler, and the default -// ogenerrors.DefaultErrorHandler maps it to HTTP 501. When the contract defines -// a default error response, the generated server still sends -// ht.ErrNotImplemented to ErrorHandler before calling NewError. The embedded -// NewError, however, returns a zero status code that the generated encoder -// sends as HTTP 200, so the composite must then define NewError explicitly. -// That NewError must answer *ogenerrors.SecurityError with 401 or 403, which -// the generated server passes to it directly, and answer every other error -// with 500 and a sanitized message, never err.Error() of an internal error. -// Errors of the generated status-code error type (*StatusCode) are -// encoded before NewError is called, so it does not need to handle them. +// server passes that error to the ErrorHandler configured in the router, which +// answers 501 with code not_implemented, before it would call NewError. +// +// The contract's common default response makes ogen add NewError to +// api.Handler. The embedded api.UnimplementedHandler.NewError returns a zero +// status code that the generated encoder sends as HTTP 200, so Handler defines +// NewError explicitly: *ogenerrors.SecurityError, which the generated server +// passes to it directly, becomes 401, and every other error becomes 500 with a +// fixed body and is logged here, never exposing err.Error(). Errors of the +// generated *api.ProblemStatusCode type are encoded before NewError is called, +// so operations return them for expected failures such as 403 or 404. // // Each implemented operation gets an explicit method here that delegates to // the handler owning it. Each implemented operation also gets a router test @@ -30,15 +31,21 @@ import ( type Handler struct { api.UnimplementedHandler - health *HealthHandler + health *HealthHandler + problems *problem.Responder } var _ api.Handler = (*Handler)(nil) -func NewHandler(health *HealthHandler) *Handler { - return &Handler{health: health} +func NewHandler(health *HealthHandler, problems *problem.Responder) *Handler { + return &Handler{health: health, problems: problems} } func (handler *Handler) GetHealthz(ctx context.Context) (*api.HealthResponse, error) { return handler.health.GetHealthz(ctx) } + +// NewError implements api.Handler for errors returned by operations. +func (handler *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode { + return handler.problems.HandlerError(ctx, err) +} diff --git a/backend/internal/adapter/primary/http/v1/handler_test.go b/backend/internal/adapter/primary/http/v1/handler_test.go index 58ce015..674cb4a 100644 --- a/backend/internal/adapter/primary/http/v1/handler_test.go +++ b/backend/internal/adapter/primary/http/v1/handler_test.go @@ -3,9 +3,12 @@ package v1 import ( "context" "errors" + "log/slog" "net/http" "reflect" "testing" + + "lincodex/backend/internal/adapter/primary/http/problem" ) // Once the contract defines a default error response, ogen adds NewError to @@ -13,7 +16,7 @@ import ( // status code, which the generated encoder sends as HTTP 200. A handler error // would then look like a success, so the composite must define its own NewError. func TestHandlerNewErrorDoesNotReportSuccess(t *testing.T) { - newError := reflect.ValueOf(NewHandler(nil)).MethodByName("NewError") + newError := reflect.ValueOf(NewHandler(nil, problem.NewResponder(slog.New(slog.DiscardHandler)))).MethodByName("NewError") if !newError.IsValid() { t.Skip("the contract has no default error response, so the generated server has no NewError") } diff --git a/backend/internal/adapter/secondary/ml/api/oas_cfg_gen.go b/backend/internal/adapter/secondary/ml/api/oas_cfg_gen.go index 62854e3..603935c 100644 --- a/backend/internal/adapter/secondary/ml/api/oas_cfg_gen.go +++ b/backend/internal/adapter/secondary/ml/api/oas_cfg_gen.go @@ -6,6 +6,7 @@ import ( "net/http" ht "github.com/ogen-go/ogen/http" + "github.com/ogen-go/ogen/ogenregex" "github.com/ogen-go/ogen/otelogen" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" @@ -13,6 +14,11 @@ import ( "go.opentelemetry.io/otel/trace" ) +var regexMap = map[string]ogenregex.Regexp{ + "^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"), + "^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"), + "^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"), +} var ( // Allocate option closure once. clientSpanKind = trace.WithSpanKind(trace.SpanKindClient) diff --git a/backend/internal/adapter/secondary/ml/api/oas_json_gen.go b/backend/internal/adapter/secondary/ml/api/oas_json_gen.go index 81d99ca..c7ae0f1 100644 --- a/backend/internal/adapter/secondary/ml/api/oas_json_gen.go +++ b/backend/internal/adapter/secondary/ml/api/oas_json_gen.go @@ -352,3 +352,519 @@ func (s *MLReadinessResponseStatus) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } + +// Encode encodes string as json. +func (o OptString) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Str(string(o.Value)) +} + +// Decode decodes string from json. +func (o *OptString) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptString to nil") + } + o.Set = true + v, err := d.Str() + if err != nil { + return err + } + o.Value = string(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptString) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptString) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *Problem) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Problem) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + e.Str(s.Type) + } + { + e.FieldStart("title") + e.Str(s.Title) + } + { + e.FieldStart("status") + e.Int32(s.Status) + } + { + e.FieldStart("code") + s.Code.Encode(e) + } + { + if s.Detail.Set { + e.FieldStart("detail") + s.Detail.Encode(e) + } + } + { + if s.Instance.Set { + e.FieldStart("instance") + s.Instance.Encode(e) + } + } + { + if s.TraceID.Set { + e.FieldStart("trace_id") + s.TraceID.Encode(e) + } + } + { + if s.Errors != nil { + e.FieldStart("errors") + e.ArrStart() + for _, elem := range s.Errors { + elem.Encode(e) + } + e.ArrEnd() + } + } +} + +var jsonFieldsNameOfProblem = [8]string{ + 0: "type", + 1: "title", + 2: "status", + 3: "code", + 4: "detail", + 5: "instance", + 6: "trace_id", + 7: "errors", +} + +// Decode decodes Problem from json. +func (s *Problem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Problem to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Type = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "title": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Title = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"title\"") + } + case "status": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int32() + s.Status = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "code": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Code.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "detail": + if err := func() error { + s.Detail.Reset() + if err := s.Detail.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"detail\"") + } + case "instance": + if err := func() error { + s.Instance.Reset() + if err := s.Instance.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"instance\"") + } + case "trace_id": + if err := func() error { + s.TraceID.Reset() + if err := s.TraceID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"trace_id\"") + } + case "errors": + if err := func() error { + s.Errors = make([]ProblemFieldError, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProblemFieldError + if err := elem.Decode(d); err != nil { + return err + } + s.Errors = append(s.Errors, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"errors\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Problem") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProblem) { + name = jsonFieldsNameOfProblem[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *Problem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Problem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProblemCode as json. +func (s ProblemCode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProblemCode from json. +func (s *ProblemCode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemCode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProblemCode(v) { + case ProblemCodeValidationFailed: + *s = ProblemCodeValidationFailed + case ProblemCodeUnauthenticated: + *s = ProblemCodeUnauthenticated + case ProblemCodeForbidden: + *s = ProblemCodeForbidden + case ProblemCodeNotFound: + *s = ProblemCodeNotFound + case ProblemCodeMethodNotAllowed: + *s = ProblemCodeMethodNotAllowed + case ProblemCodeIdempotencyInProgress: + *s = ProblemCodeIdempotencyInProgress + case ProblemCodeStateConflict: + *s = ProblemCodeStateConflict + case ProblemCodeVersionConflict: + *s = ProblemCodeVersionConflict + case ProblemCodePayloadTooLarge: + *s = ProblemCodePayloadTooLarge + case ProblemCodeUnsupportedMediaType: + *s = ProblemCodeUnsupportedMediaType + case ProblemCodeIdempotencyKeyReused: + *s = ProblemCodeIdempotencyKeyReused + case ProblemCodePreconditionRequired: + *s = ProblemCodePreconditionRequired + case ProblemCodeRateLimited: + *s = ProblemCodeRateLimited + case ProblemCodeInternal: + *s = ProblemCodeInternal + case ProblemCodeNotImplemented: + *s = ProblemCodeNotImplemented + default: + *s = ProblemCode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProblemCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProblemFieldError) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProblemFieldError) encodeFields(e *jx.Encoder) { + { + e.FieldStart("in") + s.In.Encode(e) + } + { + e.FieldStart("pointer") + e.Str(s.Pointer) + } + { + e.FieldStart("code") + e.Str(s.Code) + } + { + e.FieldStart("message") + e.Str(s.Message) + } +} + +var jsonFieldsNameOfProblemFieldError = [4]string{ + 0: "in", + 1: "pointer", + 2: "code", + 3: "message", +} + +// Decode decodes ProblemFieldError from json. +func (s *ProblemFieldError) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemFieldError to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "in": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.In.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"in\"") + } + case "pointer": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Pointer = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"pointer\"") + } + case "code": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.Code = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "message": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Str() + s.Message = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"message\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProblemFieldError") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProblemFieldError) { + name = jsonFieldsNameOfProblemFieldError[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProblemFieldError) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemFieldError) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProblemFieldLocation as json. +func (s ProblemFieldLocation) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProblemFieldLocation from json. +func (s *ProblemFieldLocation) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProblemFieldLocation to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProblemFieldLocation(v) { + case ProblemFieldLocationBody: + *s = ProblemFieldLocationBody + case ProblemFieldLocationQuery: + *s = ProblemFieldLocationQuery + case ProblemFieldLocationPath: + *s = ProblemFieldLocationPath + case ProblemFieldLocationHeader: + *s = ProblemFieldLocationHeader + case ProblemFieldLocationCookie: + *s = ProblemFieldLocationCookie + default: + *s = ProblemFieldLocation(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProblemFieldLocation) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProblemFieldLocation) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} diff --git a/backend/internal/adapter/secondary/ml/api/oas_response_decoders_gen.go b/backend/internal/adapter/secondary/ml/api/oas_response_decoders_gen.go index b3b771e..e094ac2 100644 --- a/backend/internal/adapter/secondary/ml/api/oas_response_decoders_gen.go +++ b/backend/internal/adapter/secondary/ml/api/oas_response_decoders_gen.go @@ -60,7 +60,58 @@ func decodeGetMLHealthzResponse(resp *http.Response) (res *MLHealthResponse, _ e return res, validate.InvalidContentType(ct) } } - return res, validate.UnexpectedStatusCodeWithResponse(resp) + // Convenient error response. + defRes, err := func() (res *ProblemStatusCode, err error) { + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/problem+json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response Problem + if err := func() error { + if err := response.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &ProblemStatusCode{ + StatusCode: resp.StatusCode, + Response: response, + }, nil + default: + return res, validate.InvalidContentType(ct) + } + }() + if err != nil { + return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode) + } + return res, errors.Wrap(defRes, "error") } func decodeGetMLReadyzResponse(resp *http.Response) (res GetMLReadyzRes, _ error) { @@ -154,5 +205,56 @@ func decodeGetMLReadyzResponse(resp *http.Response) (res GetMLReadyzRes, _ error return res, validate.InvalidContentType(ct) } } - return res, validate.UnexpectedStatusCodeWithResponse(resp) + // Convenient error response. + defRes, err := func() (res *ProblemStatusCode, err error) { + ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil { + return res, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/problem+json": + buf, err := io.ReadAll(resp.Body) + if err != nil { + return res, err + } + d := jx.DecodeBytes(buf) + + var response Problem + if err := func() error { + if err := response.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return res, err + } + // Validate response. + if err := func() error { + if err := response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + return &ProblemStatusCode{ + StatusCode: resp.StatusCode, + Response: response, + }, nil + default: + return res, validate.InvalidContentType(ct) + } + }() + if err != nil { + return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode) + } + return res, errors.Wrap(defRes, "error") } diff --git a/backend/internal/adapter/secondary/ml/api/oas_schemas_gen.go b/backend/internal/adapter/secondary/ml/api/oas_schemas_gen.go index eabdc80..04f29fd 100644 --- a/backend/internal/adapter/secondary/ml/api/oas_schemas_gen.go +++ b/backend/internal/adapter/secondary/ml/api/oas_schemas_gen.go @@ -3,9 +3,15 @@ package api import ( + "fmt" + "github.com/go-faster/errors" ) +func (s *ProblemStatusCode) Error() string { + return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response) +} + type GetMLReadyzOK MLReadinessResponse func (*GetMLReadyzOK) getMLReadyzRes() {} @@ -118,3 +124,454 @@ func (s *MLReadinessResponseStatus) UnmarshalText(data []byte) error { return errors.Errorf("invalid value: %q", data) } } + +// NewOptString returns new OptString with value set to v. +func NewOptString(v string) OptString { + return OptString{ + Value: v, + Set: true, + } +} + +// OptString is optional string. +type OptString struct { + Value string + Set bool +} + +// IsSet returns true if OptString was set. +func (o OptString) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptString) Reset() { + var v string + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptString) SetTo(v string) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptString) Get() (v string, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptString) Or(d string) string { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// Problem details (RFC 9457) returned with the application/problem+json media type for every error +// response. This is the ML service copy of the public api/core Problem schema; keep both copies +// identical except for descriptions. `code` is the stable, machine-readable reason; clients branch on +// it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal +// error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. +// Ref: #/components/schemas/Problem +type Problem struct { + // URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an + // identifier, not a link to dereference. + Type string `json:"type"` + // Short, fixed English summary of the problem type. It does not change between occurrences. + Title string `json:"title"` + // HTTP status code generated by the origin server. + Status int32 `json:"status"` + Code ProblemCode `json:"code"` + // Safe English explanation of this occurrence. It never contains internal error text or request + // values. + Detail OptString `json:"detail"` + // URI reference that identifies this occurrence, when one exists. + Instance OptString `json:"instance"` + // Request identifier of the call when the caller propagated one; it is not a secret. + TraceID OptString `json:"trace_id"` + // Field-level reasons for validation_failed. Other codes omit it. + Errors []ProblemFieldError `json:"errors"` +} + +// GetType returns the value of Type. +func (s *Problem) GetType() string { + return s.Type +} + +// GetTitle returns the value of Title. +func (s *Problem) GetTitle() string { + return s.Title +} + +// GetStatus returns the value of Status. +func (s *Problem) GetStatus() int32 { + return s.Status +} + +// GetCode returns the value of Code. +func (s *Problem) GetCode() ProblemCode { + return s.Code +} + +// GetDetail returns the value of Detail. +func (s *Problem) GetDetail() OptString { + return s.Detail +} + +// GetInstance returns the value of Instance. +func (s *Problem) GetInstance() OptString { + return s.Instance +} + +// GetTraceID returns the value of TraceID. +func (s *Problem) GetTraceID() OptString { + return s.TraceID +} + +// GetErrors returns the value of Errors. +func (s *Problem) GetErrors() []ProblemFieldError { + return s.Errors +} + +// SetType sets the value of Type. +func (s *Problem) SetType(val string) { + s.Type = val +} + +// SetTitle sets the value of Title. +func (s *Problem) SetTitle(val string) { + s.Title = val +} + +// SetStatus sets the value of Status. +func (s *Problem) SetStatus(val int32) { + s.Status = val +} + +// SetCode sets the value of Code. +func (s *Problem) SetCode(val ProblemCode) { + s.Code = val +} + +// SetDetail sets the value of Detail. +func (s *Problem) SetDetail(val OptString) { + s.Detail = val +} + +// SetInstance sets the value of Instance. +func (s *Problem) SetInstance(val OptString) { + s.Instance = val +} + +// SetTraceID sets the value of TraceID. +func (s *Problem) SetTraceID(val OptString) { + s.TraceID = val +} + +// SetErrors sets the value of Errors. +func (s *Problem) SetErrors(val []ProblemFieldError) { + s.Errors = val +} + +// Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking +// change. Clients must handle an unknown code by its HTTP status. +// +// - validation_failed (400): parameters or body do not match the contract, or a body violates a +// domain rule such as salary_from <= salary_to; `errors` points at the fields. +// - unauthenticated (401): no valid session or credentials. +// - forbidden (403): the caller is authenticated but not allowed. +// - not_found (404): the route or object does not exist or is not visible. +// - method_not_allowed (405): the route does not support the method. +// - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. +// - state_conflict (409): the operation conflicts with the current state of the resource, for example +// an invitation that was already accepted. +// - version_conflict (412): If-Match does not match the current version. +// - payload_too_large (413): the request body exceeds the limit. +// - unsupported_media_type (415): the request Content-Type is not accepted. +// - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. +// - precondition_required (428): the operation requires If-Match. +// - rate_limited (429): too many requests; see Retry-After. +// - internal (500): unexpected server error. +// - not_implemented (501): the operation is in the contract but not implemented yet. +// +// Ref: #/components/schemas/ProblemCode +type ProblemCode string + +const ( + ProblemCodeValidationFailed ProblemCode = "validation_failed" + ProblemCodeUnauthenticated ProblemCode = "unauthenticated" + ProblemCodeForbidden ProblemCode = "forbidden" + ProblemCodeNotFound ProblemCode = "not_found" + ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed" + ProblemCodeIdempotencyInProgress ProblemCode = "idempotency_in_progress" + ProblemCodeStateConflict ProblemCode = "state_conflict" + ProblemCodeVersionConflict ProblemCode = "version_conflict" + ProblemCodePayloadTooLarge ProblemCode = "payload_too_large" + ProblemCodeUnsupportedMediaType ProblemCode = "unsupported_media_type" + ProblemCodeIdempotencyKeyReused ProblemCode = "idempotency_key_reused" + ProblemCodePreconditionRequired ProblemCode = "precondition_required" + ProblemCodeRateLimited ProblemCode = "rate_limited" + ProblemCodeInternal ProblemCode = "internal" + ProblemCodeNotImplemented ProblemCode = "not_implemented" +) + +// AllValues returns all ProblemCode values. +func (ProblemCode) AllValues() []ProblemCode { + return []ProblemCode{ + ProblemCodeValidationFailed, + ProblemCodeUnauthenticated, + ProblemCodeForbidden, + ProblemCodeNotFound, + ProblemCodeMethodNotAllowed, + ProblemCodeIdempotencyInProgress, + ProblemCodeStateConflict, + ProblemCodeVersionConflict, + ProblemCodePayloadTooLarge, + ProblemCodeUnsupportedMediaType, + ProblemCodeIdempotencyKeyReused, + ProblemCodePreconditionRequired, + ProblemCodeRateLimited, + ProblemCodeInternal, + ProblemCodeNotImplemented, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProblemCode) MarshalText() ([]byte, error) { + switch s { + case ProblemCodeValidationFailed: + return []byte(s), nil + case ProblemCodeUnauthenticated: + return []byte(s), nil + case ProblemCodeForbidden: + return []byte(s), nil + case ProblemCodeNotFound: + return []byte(s), nil + case ProblemCodeMethodNotAllowed: + return []byte(s), nil + case ProblemCodeIdempotencyInProgress: + return []byte(s), nil + case ProblemCodeStateConflict: + return []byte(s), nil + case ProblemCodeVersionConflict: + return []byte(s), nil + case ProblemCodePayloadTooLarge: + return []byte(s), nil + case ProblemCodeUnsupportedMediaType: + return []byte(s), nil + case ProblemCodeIdempotencyKeyReused: + return []byte(s), nil + case ProblemCodePreconditionRequired: + return []byte(s), nil + case ProblemCodeRateLimited: + return []byte(s), nil + case ProblemCodeInternal: + return []byte(s), nil + case ProblemCodeNotImplemented: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProblemCode) UnmarshalText(data []byte) error { + switch ProblemCode(data) { + case ProblemCodeValidationFailed: + *s = ProblemCodeValidationFailed + return nil + case ProblemCodeUnauthenticated: + *s = ProblemCodeUnauthenticated + return nil + case ProblemCodeForbidden: + *s = ProblemCodeForbidden + return nil + case ProblemCodeNotFound: + *s = ProblemCodeNotFound + return nil + case ProblemCodeMethodNotAllowed: + *s = ProblemCodeMethodNotAllowed + return nil + case ProblemCodeIdempotencyInProgress: + *s = ProblemCodeIdempotencyInProgress + return nil + case ProblemCodeStateConflict: + *s = ProblemCodeStateConflict + return nil + case ProblemCodeVersionConflict: + *s = ProblemCodeVersionConflict + return nil + case ProblemCodePayloadTooLarge: + *s = ProblemCodePayloadTooLarge + return nil + case ProblemCodeUnsupportedMediaType: + *s = ProblemCodeUnsupportedMediaType + return nil + case ProblemCodeIdempotencyKeyReused: + *s = ProblemCodeIdempotencyKeyReused + return nil + case ProblemCodePreconditionRequired: + *s = ProblemCodePreconditionRequired + return nil + case ProblemCodeRateLimited: + *s = ProblemCodeRateLimited + return nil + case ProblemCodeInternal: + *s = ProblemCodeInternal + return nil + case ProblemCodeNotImplemented: + *s = ProblemCodeNotImplemented + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One reason why a request field or parameter is invalid. +// Ref: #/components/schemas/ProblemFieldError +type ProblemFieldError struct { + In ProblemFieldLocation `json:"in"` + // JSON Pointer (RFC 6901). For `body` it points into the request body document, for example + // `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the + // parameter name, for example `/limit` or `/Idempotency-Key`. + Pointer string `json:"pointer"` + // Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or + // a value outside the schema). Clients must tolerate new values. + Code string `json:"code"` + // Fixed English message that never echoes the submitted value. + Message string `json:"message"` +} + +// GetIn returns the value of In. +func (s *ProblemFieldError) GetIn() ProblemFieldLocation { + return s.In +} + +// GetPointer returns the value of Pointer. +func (s *ProblemFieldError) GetPointer() string { + return s.Pointer +} + +// GetCode returns the value of Code. +func (s *ProblemFieldError) GetCode() string { + return s.Code +} + +// GetMessage returns the value of Message. +func (s *ProblemFieldError) GetMessage() string { + return s.Message +} + +// SetIn sets the value of In. +func (s *ProblemFieldError) SetIn(val ProblemFieldLocation) { + s.In = val +} + +// SetPointer sets the value of Pointer. +func (s *ProblemFieldError) SetPointer(val string) { + s.Pointer = val +} + +// SetCode sets the value of Code. +func (s *ProblemFieldError) SetCode(val string) { + s.Code = val +} + +// SetMessage sets the value of Message. +func (s *ProblemFieldError) SetMessage(val string) { + s.Message = val +} + +// Part of the request that contains the invalid field. +// Ref: #/components/schemas/ProblemFieldLocation +type ProblemFieldLocation string + +const ( + ProblemFieldLocationBody ProblemFieldLocation = "body" + ProblemFieldLocationQuery ProblemFieldLocation = "query" + ProblemFieldLocationPath ProblemFieldLocation = "path" + ProblemFieldLocationHeader ProblemFieldLocation = "header" + ProblemFieldLocationCookie ProblemFieldLocation = "cookie" +) + +// AllValues returns all ProblemFieldLocation values. +func (ProblemFieldLocation) AllValues() []ProblemFieldLocation { + return []ProblemFieldLocation{ + ProblemFieldLocationBody, + ProblemFieldLocationQuery, + ProblemFieldLocationPath, + ProblemFieldLocationHeader, + ProblemFieldLocationCookie, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProblemFieldLocation) MarshalText() ([]byte, error) { + switch s { + case ProblemFieldLocationBody: + return []byte(s), nil + case ProblemFieldLocationQuery: + return []byte(s), nil + case ProblemFieldLocationPath: + return []byte(s), nil + case ProblemFieldLocationHeader: + return []byte(s), nil + case ProblemFieldLocationCookie: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProblemFieldLocation) UnmarshalText(data []byte) error { + switch ProblemFieldLocation(data) { + case ProblemFieldLocationBody: + *s = ProblemFieldLocationBody + return nil + case ProblemFieldLocationQuery: + *s = ProblemFieldLocationQuery + return nil + case ProblemFieldLocationPath: + *s = ProblemFieldLocationPath + return nil + case ProblemFieldLocationHeader: + *s = ProblemFieldLocationHeader + return nil + case ProblemFieldLocationCookie: + *s = ProblemFieldLocationCookie + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// ProblemStatusCode wraps Problem with StatusCode. +type ProblemStatusCode struct { + StatusCode int + Response Problem +} + +// GetStatusCode returns the value of StatusCode. +func (s *ProblemStatusCode) GetStatusCode() int { + return s.StatusCode +} + +// GetResponse returns the value of Response. +func (s *ProblemStatusCode) GetResponse() Problem { + return s.Response +} + +// SetStatusCode sets the value of StatusCode. +func (s *ProblemStatusCode) SetStatusCode(val int) { + s.StatusCode = val +} + +// SetResponse sets the value of Response. +func (s *ProblemStatusCode) SetResponse(val Problem) { + s.Response = val +} diff --git a/backend/internal/adapter/secondary/ml/api/oas_validators_gen.go b/backend/internal/adapter/secondary/ml/api/oas_validators_gen.go index d44c84c..9503c58 100644 --- a/backend/internal/adapter/secondary/ml/api/oas_validators_gen.go +++ b/backend/internal/adapter/secondary/ml/api/oas_validators_gen.go @@ -3,6 +3,8 @@ package api import ( + "fmt" + "github.com/go-faster/errors" "github.com/ogen-go/ogen/validate" ) @@ -88,3 +90,388 @@ func (s MLReadinessResponseStatus) Validate() error { return errors.Errorf("invalid value: %v", s) } } + +func (s *Problem) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 256, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Type)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Title)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "title", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 400, + MaxSet: true, + Max: 599, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Status)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if err := s.Code.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Detail.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "detail", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Instance.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2048, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "instance", + Error: err, + }) + } + if err := func() error { + if value, ok := s.TraceID.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "trace_id", + Error: err, + }) + } + if err := func() error { + if s.Errors == nil { + return nil // optional + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 100, + MaxLengthSet: true, + }).ValidateLength(len(s.Errors)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Errors { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "errors", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProblemCode) Validate() error { + switch s { + case "validation_failed": + return nil + case "unauthenticated": + return nil + case "forbidden": + return nil + case "not_found": + return nil + case "method_not_allowed": + return nil + case "idempotency_in_progress": + return nil + case "state_conflict": + return nil + case "version_conflict": + return nil + case "payload_too_large": + return nil + case "unsupported_media_type": + return nil + case "idempotency_key_reused": + return nil + case "precondition_required": + return nil + case "rate_limited": + return nil + case "internal": + return nil + case "not_implemented": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ProblemFieldError) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.In.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "in", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 1024, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^(/([^~/]|~[01])*)*$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Pointer)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "pointer", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 64, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[a-z][a-z0-9_]*$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Code)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 500, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Message)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "message", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProblemFieldLocation) Validate() error { + switch s { + case "body": + return nil + case "query": + return nil + case "path": + return nil + case "header": + return nil + case "cookie": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ProblemStatusCode) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index d698bfa..0034561 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -12,6 +12,7 @@ import ( httpadapter "lincodex/backend/internal/adapter/primary/http" apiadapter "lincodex/backend/internal/adapter/primary/http/api" httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware" + "lincodex/backend/internal/adapter/primary/http/problem" v1 "lincodex/backend/internal/adapter/primary/http/v1" "lincodex/backend/internal/adapter/secondary/postgres" metrics "lincodex/backend/internal/adapter/secondary/prometheus" @@ -33,6 +34,7 @@ func initialize(ctx context.Context, config config.Config, logger *slog.Logger) newReadiness, metrics.New, newHealthHandler, + problem.NewResponder, v1.NewHandler, httpadapter.NewRouter, NewApplication, diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index c95c8ba..0fdd413 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -10,6 +10,7 @@ import ( "context" "lincodex/backend/config" "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" "lincodex/backend/internal/adapter/primary/http/v1" "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/prometheus" @@ -40,9 +41,10 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger) } readiness := newReadiness(healthChecker, cache, storage) healthHandler := newHealthHandler(readiness, config2) - handler := v1.NewHandler(healthHandler) + responder := problem.NewResponder(logger) + handler := v1.NewHandler(healthHandler, responder) metrics := prometheus.New() - httpHandler, err := httpadapter.NewRouter(healthHandler, handler, metrics, logger) + httpHandler, err := httpadapter.NewRouter(healthHandler, handler, responder, metrics, logger) if err != nil { cleanup3() cleanup2() diff --git a/backend/testdata/ogen_compat_test.go b/backend/testdata/ogen_compat_test.go index 5de7202..f04567d 100644 --- a/backend/testdata/ogen_compat_test.go +++ b/backend/testdata/ogen_compat_test.go @@ -3,30 +3,160 @@ package compat import ( "context" "encoding/json" + "log/slog" "net/http" "net/http/httptest" + "reflect" + "strings" + "sync" "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/http/problem" ) -type compatibilityHandler struct{} +const ( + defaultPageLimit = 20 + fixtureETag = `"v2"` + staleETag = `"v1"` +) -func (compatibilityHandler) GetProbe(context.Context, GetProbeParams) (*NullablePayload, error) { +var fixtureUpdatedAt = time.Date(2026, time.October, 5, 9, 30, 0, 0, time.UTC) + +// compatibilityHandler implements the fixture operations. CreateProbeItem keeps +// a minimal in-memory idempotency record so the test can show that the +// generated types express the contract's retry scenario; it is not product +// behavior. +type compatibilityHandler struct { + mu sync.Mutex + requests map[string]string + responses map[string]*ProbeItemHeaders + lastLimit int32 +} + +func newCompatibilityHandler() *compatibilityHandler { + return &compatibilityHandler{requests: map[string]string{}, responses: map[string]*ProbeItemHeaders{}} +} + +func (*compatibilityHandler) GetProbe(context.Context, GetProbeParams) (*NullablePayload, error) { return &NullablePayload{}, nil } -func (compatibilityHandler) PurgeProbe(context.Context) error { +func (*compatibilityHandler) PurgeProbe(context.Context) error { return nil } -func TestGeneratedServerRejectsInvalidInput(t *testing.T) { - server, err := NewServer(compatibilityHandler{}) +func (handler *compatibilityHandler) ListProbeItems(_ context.Context, params ListProbeItemsParams) (*ProbeItemPage, error) { + handler.mu.Lock() + handler.lastLimit = params.Limit.Or(0) + handler.mu.Unlock() + return &ProbeItemPage{Items: []ProbeItem{}, Page: PageInfo{HasMore: false, NextCursor: NilString{Null: true}}}, nil +} + +func (handler *compatibilityHandler) CreateProbeItem(_ context.Context, request *ProbeItemInput, params CreateProbeItemParams) (CreateProbeItemRes, error) { + handler.mu.Lock() + defer handler.mu.Unlock() + if fingerprint, seen := handler.requests[params.IdempotencyKey]; seen { + if fingerprint != request.Name { + reused := CreateProbeItemUnprocessableEntity(fixtureProblem(http.StatusUnprocessableEntity, ProblemCodeIdempotencyKeyReused)) + return &reused, nil + } + return handler.responses[params.IdempotencyKey], nil + } + response := &ProbeItemHeaders{ + ETag: fixtureETag, + Response: ProbeItem{ID: uuid.New(), Name: request.Name, UpdatedAt: Timestamp(fixtureUpdatedAt)}, + } + handler.requests[params.IdempotencyKey] = request.Name + handler.responses[params.IdempotencyKey] = response + return response, nil +} + +func (*compatibilityHandler) UpdateProbeItem(_ context.Context, request *ProbeItemInput, params UpdateProbeItemParams) (UpdateProbeItemRes, error) { + ifMatch, ok := params.IfMatch.Get() + if !ok { + required := UpdateProbeItemPreconditionRequired(fixtureProblem(http.StatusPreconditionRequired, ProblemCodePreconditionRequired)) + return &required, nil + } + if ifMatch != fixtureETag { + conflict := UpdateProbeItemPreconditionFailed(fixtureProblem(http.StatusPreconditionFailed, ProblemCodeVersionConflict)) + return &conflict, nil + } + return &ProbeItemHeaders{ + ETag: `"v3"`, + Response: ProbeItem{ID: params.ItemID, Name: request.Name, UpdatedAt: Timestamp(fixtureUpdatedAt)}, + }, nil +} + +func (*compatibilityHandler) NewError(context.Context, error) *ProblemStatusCode { + return &ProblemStatusCode{StatusCode: http.StatusInternalServerError, Response: fixtureProblem(http.StatusInternalServerError, ProblemCodeInternal)} +} + +func fixtureProblem(status int32, code ProblemCode) Problem { + return Problem{Type: "urn:lincodex:problem:" + string(code), Title: "Fixture problem", Status: status, Code: code} +} + +// newServer mounts the fixture with the backend's problem mapping, so decoding +// and validation errors produced by real generated code are checked against +// the public error contract. +func newServer(t *testing.T, handler Handler) *Server { + t.Helper() + problems := problem.NewResponder(slog.New(slog.DiscardHandler)) + server, err := NewServer(handler, + WithErrorHandler(problems.HandleServerError), + WithNotFound(problems.NotFound), + WithMethodNotAllowed(problems.MethodNotAllowed), + ) if err != nil { t.Fatalf("NewServer() error = %v", err) } + return server +} + +func serve(t *testing.T, server http.Handler, method, target, body string, headers map[string]string) *httptest.ResponseRecorder { + t.Helper() + request := httptest.NewRequest(method, target, strings.NewReader(body)) + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + for name, value := range headers { + request.Header.Set(name, value) + } response := httptest.NewRecorder() - server.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/probe?state=invalid", nil)) - if response.Code != http.StatusBadRequest { - t.Fatalf("status code = %d, want %d", response.Code, http.StatusBadRequest) + server.ServeHTTP(response, request) + return response +} + +func decodeProblem(t *testing.T, response *httptest.ResponseRecorder, status int, code ProblemCode) Problem { + t.Helper() + if response.Code != status { + t.Fatalf("status code = %d, want %d: %s", response.Code, status, response.Body.String()) + } + if contentType := response.Header().Get("Content-Type"); contentType != problem.MediaType { + t.Fatalf("Content-Type = %q, want %q", contentType, problem.MediaType) + } + var body Problem + if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil { + t.Fatalf("decode problem %s: %v", response.Body.String(), err) + } + if err := body.Validate(); err != nil { + t.Fatalf("problem %s violates the contract: %v", response.Body.String(), err) + } + if body.Code != code || int(body.Status) != status { + t.Fatalf("problem code/status = %q/%d, want %q/%d", body.Code, body.Status, code, status) + } + return body +} + +func TestGeneratedServerRejectsInvalidInput(t *testing.T) { + server := newServer(t, newCompatibilityHandler()) + response := serve(t, server, http.MethodGet, "/probe?state=invalid", "", nil) + body := decodeProblem(t, response, http.StatusBadRequest, ProblemCodeValidationFailed) + want := []ProblemFieldError{{In: ProblemFieldLocationQuery, Pointer: "/state", Code: "invalid", Message: "The value does not match the contract."}} + if !reflect.DeepEqual(body.Errors, want) { + t.Fatalf("errors = %+v, want %+v", body.Errors, want) } } @@ -41,13 +171,134 @@ func TestNullableTypeArrayPreservesNull(t *testing.T) { } func TestAdditionalOperationIsRouted(t *testing.T) { - server, err := NewServer(compatibilityHandler{}) - if err != nil { - t.Fatalf("NewServer() error = %v", err) - } - response := httptest.NewRecorder() - server.ServeHTTP(response, httptest.NewRequest("PURGE", "/probe", nil)) + server := newServer(t, newCompatibilityHandler()) + response := serve(t, server, "PURGE", "/probe", "", nil) if response.Code != http.StatusNoContent { t.Fatalf("status code = %d, want %d", response.Code, http.StatusNoContent) } } + +func TestGeneratedValidationErrorsMapToProblemFields(t *testing.T) { + validKey := map[string]string{"Idempotency-Key": "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11"} + for _, test := range []struct { + name string + method string + target string + body string + headers map[string]string + field ProblemFieldError + }{ + {name: "limit below range", method: http.MethodGet, target: "/probe/items?limit=0", field: invalidField(ProblemFieldLocationQuery, "/limit")}, + {name: "limit above range", method: http.MethodGet, target: "/probe/items?limit=101", field: invalidField(ProblemFieldLocationQuery, "/limit")}, + {name: "cursor too long", method: http.MethodGet, target: "/probe/items?cursor=" + strings.Repeat("a", 513), field: invalidField(ProblemFieldLocationQuery, "/cursor")}, + {name: "cursor charset", method: http.MethodGet, target: "/probe/items?cursor=a+b", field: invalidField(ProblemFieldLocationQuery, "/cursor")}, + {name: "missing idempotency key", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe"}`, field: requiredField(ProblemFieldLocationHeader, "/Idempotency-Key")}, + {name: "idempotency key too long", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": strings.Repeat("k", 256)}, field: invalidField(ProblemFieldLocationHeader, "/Idempotency-Key")}, + {name: "idempotency key charset", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": "key with spaces"}, field: invalidField(ProblemFieldLocationHeader, "/Idempotency-Key")}, + {name: "weak if-match", method: http.MethodPatch, target: "/probe/items/" + uuid.NewString(), body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": "k1", "If-Match": `W/"v2"`}, field: invalidField(ProblemFieldLocationHeader, "/If-Match")}, + {name: "invalid path id", method: http.MethodPatch, target: "/probe/items/not-a-uuid", body: `{"name":"probe"}`, headers: map[string]string{"Idempotency-Key": "k1"}, field: invalidField(ProblemFieldLocationPath, "/item_id")}, + {name: "missing body", method: http.MethodPost, target: "/probe/items", headers: map[string]string{"Idempotency-Key": "k1", "Content-Type": "application/json"}, field: requiredField(ProblemFieldLocationBody, "")}, + {name: "missing body field", method: http.MethodPost, target: "/probe/items", body: `{}`, headers: validKey, field: requiredField(ProblemFieldLocationBody, "/name")}, + {name: "body field too long", method: http.MethodPost, target: "/probe/items", body: `{"name":"` + strings.Repeat("n", 101) + `"}`, headers: validKey, field: invalidField(ProblemFieldLocationBody, "/name")}, + {name: "unknown body field", method: http.MethodPost, target: "/probe/items", body: `{"name":"probe","extra":true}`, headers: validKey, field: invalidField(ProblemFieldLocationBody, "")}, + {name: "malformed body", method: http.MethodPost, target: "/probe/items", body: `{"name":`, headers: validKey, field: invalidField(ProblemFieldLocationBody, "")}, + } { + t.Run(test.name, func(t *testing.T) { + server := newServer(t, newCompatibilityHandler()) + response := serve(t, server, test.method, test.target, test.body, test.headers) + body := decodeProblem(t, response, http.StatusBadRequest, ProblemCodeValidationFailed) + if want := []ProblemFieldError{test.field}; !reflect.DeepEqual(body.Errors, want) { + t.Fatalf("errors = %+v, want %+v", body.Errors, want) + } + if strings.Contains(response.Body.String(), "nnnnn") || strings.Contains(response.Body.String(), "spaces") { + t.Fatalf("problem echoes the submitted value: %s", response.Body.String()) + } + }) + } +} + +func TestUnsupportedRequestMediaTypeIsRejected(t *testing.T) { + server := newServer(t, newCompatibilityHandler()) + response := serve(t, server, http.MethodPost, "/probe/items", "name", map[string]string{"Idempotency-Key": "k1", "Content-Type": "text/plain"}) + decodeProblem(t, response, http.StatusUnsupportedMediaType, ProblemCodeUnsupportedMediaType) +} + +// A body limit applied with http.MaxBytesReader reaches the problem mapping +// through the generated request decoder. +func TestBodyOverLimitIsRejected(t *testing.T) { + const bodyLimit = 16 + server := newServer(t, newCompatibilityHandler()) + limited := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, bodyLimit) + server.ServeHTTP(w, r) + }) + request := httptest.NewRequest(http.MethodPost, "/probe/items", strings.NewReader(`{"name":"`+strings.Repeat("n", 64)+`"}`)) + request.Header.Set("Content-Type", "application/json") + request.Header.Set("Idempotency-Key", "k1") + response := httptest.NewRecorder() + + limited.ServeHTTP(response, request) + + decodeProblem(t, response, http.StatusRequestEntityTooLarge, ProblemCodePayloadTooLarge) +} + +func TestPaginationAppliesDefaultLimitAndEncodesLastPage(t *testing.T) { + handler := newCompatibilityHandler() + response := serve(t, newServer(t, handler), http.MethodGet, "/probe/items", "", nil) + if response.Code != http.StatusOK { + t.Fatalf("status code = %d: %s", response.Code, response.Body.String()) + } + if handler.lastLimit != defaultPageLimit { + t.Fatalf("limit = %d, want the contract default %d", handler.lastLimit, defaultPageLimit) + } + if !strings.Contains(response.Body.String(), `"page":{"has_more":false,"next_cursor":null}`) { + t.Fatalf("last page = %s, want an explicit null cursor", response.Body.String()) + } +} + +// The same Idempotency-Key with the same body replays the stored response; the +// same key with a different body is rejected with idempotency_key_reused. +func TestIdempotencyRetryScenario(t *testing.T) { + server := newServer(t, newCompatibilityHandler()) + key := map[string]string{"Idempotency-Key": "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11"} + + first := serve(t, server, http.MethodPost, "/probe/items", `{"name":"probe"}`, key) + if first.Code != http.StatusCreated || first.Header().Get("ETag") != fixtureETag { + t.Fatalf("first response = %d ETag %q: %s", first.Code, first.Header().Get("ETag"), first.Body.String()) + } + if !strings.Contains(first.Body.String(), `"updated_at":"2026-10-05T09:30:00Z"`) { + t.Fatalf("timestamp is not UTC RFC 3339: %s", first.Body.String()) + } + + replay := serve(t, server, http.MethodPost, "/probe/items", `{"name":"probe"}`, key) + if replay.Code != http.StatusCreated || replay.Body.String() != first.Body.String() { + t.Fatalf("replay = %d %s, want the stored response %s", replay.Code, replay.Body.String(), first.Body.String()) + } + + reused := serve(t, server, http.MethodPost, "/probe/items", `{"name":"other"}`, key) + decodeProblem(t, reused, http.StatusUnprocessableEntity, ProblemCodeIdempotencyKeyReused) +} + +func TestIfMatchPreconditions(t *testing.T) { + server := newServer(t, newCompatibilityHandler()) + target := "/probe/items/" + uuid.NewString() + + missing := serve(t, server, http.MethodPatch, target, `{"name":"probe"}`, map[string]string{"Idempotency-Key": "k1"}) + decodeProblem(t, missing, http.StatusPreconditionRequired, ProblemCodePreconditionRequired) + + stale := serve(t, server, http.MethodPatch, target, `{"name":"probe"}`, map[string]string{"Idempotency-Key": "k2", "If-Match": staleETag}) + decodeProblem(t, stale, http.StatusPreconditionFailed, ProblemCodeVersionConflict) + + current := serve(t, server, http.MethodPatch, target, `{"name":"probe"}`, map[string]string{"Idempotency-Key": "k3", "If-Match": fixtureETag}) + if current.Code != http.StatusOK || current.Header().Get("ETag") != `"v3"` { + t.Fatalf("update = %d ETag %q: %s", current.Code, current.Header().Get("ETag"), current.Body.String()) + } +} + +func invalidField(in ProblemFieldLocation, pointer string) ProblemFieldError { + return ProblemFieldError{In: in, Pointer: pointer, Code: "invalid", Message: "The value does not match the contract."} +} + +func requiredField(in ProblemFieldLocation, pointer string) ProblemFieldError { + return ProblemFieldError{In: in, Pointer: pointer, Code: "required", Message: "The value is required."} +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 9b1316e..c049e31 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -88,6 +88,7 @@ backend/ adapter/primary/http/ api/ generated ogen handler middleware/ request metrics + problem/ RFC 9457 error responses v1/ handwritten health endpoint router.go chi composition adapter/secondary/ @@ -230,7 +231,7 @@ Vacancies and voluntary applications, recurring assessments, employer complaints Examples of stable operations are `POST /api/v1/searches`, `POST /api/v1/searches/{id}/refinements`, `POST /api/v1/candidates/{id}/invitations`, and `POST /api/v1/invitations/{id}/accept`. These are target examples, not implemented endpoints. Every business operation, response, and error belongs in OpenAPI with a stable `operationId`. -Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amounts for the MVP, and bounded cursor pagination. Distinguish null from absent fields. Errors have a stable `code`, safe message, optional field errors, and request ID. Use idempotency keys for invitation creation, analysis start, and assessment submission; scope keys by actor and operation, and reject reuse with a different body. Check access for every object ID, job, search run, and PDF. Never include contacts in common errors or public examples. +Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amounts for the MVP, and bounded cursor pagination. Distinguish null from absent fields. Errors have a stable `code`, safe message, optional field errors, and request ID. Use idempotency keys for invitation creation, analysis start, and assessment submission; scope keys by actor and operation, and reject reuse with a different body. Check access for every object ID, job, search run, and PDF. Never include contacts in common errors or public examples. The contract fixes the error model, Idempotency-Key, If-Match, pagination, and time format in [api/README.en.md](../../api/README.en.md#contract-conventions); of these, only the problem-based error mapping is implemented. ## Metrics, telemetry, and alerts diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index 2e3cdf1..ad2d8e2 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -112,6 +112,8 @@ The target is OpenAPI 3.2.0, with ogen for Go, Orval for TypeScript, and datamod datamodel-code-generator 0.83.0 reads api/ml/openapi.bundle.yml and writes ml/src/lincodex_ml/api/models.py. Settings live in ml/codegen/pyproject.toml; this file configures the tool, while dependencies remain in ml/pyproject.toml and uv.lock. Health/readiness handlers import the generated models instead of maintaining handwritten schema copies. make -C ml generate bundles the API first; when called by root make generate, API_PREPARED=1 reuses the prepared bundle. make -C ml check-generated compares output with --check without rewriting the file. CI uses the shared make generate target, which includes the Python models. +Errors, retries, versions, pagination, and time follow the [contract conventions](../../api/README.en.md#contract-conventions). Implemented: every error of the public Go API and of the ML service is an RFC 9457 problem (`application/problem+json`) with a stable `code`. The Go mapping of ogen errors lives in backend/internal/adapter/primary/http/problem/: request validation gives 400, unknown routes under /api 404, unimplemented operations 501, and other errors and panics 500 without internal text; errors are logged at that boundary, panics only by type and stack. The frontend API client throws `ApiRequestError` for problems, network failures (`network_error`), and invalid 2xx bodies (`invalid_response`); a caller's abort propagates unchanged. The ML service maps FastAPI errors in ml/src/lincodex_ml/api/problems.py and routes uvicorn logs through its JSON format without exception text. Idempotency-Key storage, If-Match checks, and pagination are planned: the contract defines their components, and the first business operation that needs them implements them. + ## Code boundaries SQL linter dependencies are listed in `backend/requirements-quality.txt` beside `.sqlfluff`. The `make -C backend lint-sql` command installs them in the local `.venv-quality` environment and checks migrations and queries. Running the Go service does not require this environment. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 1a9a288..3073f58 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -88,6 +88,7 @@ backend/ adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов + problem/ ответы об ошибках по RFC 9457 v1/ написанный вручную health endpoint router.go сборка chi router adapter/secondary/ @@ -230,7 +231,7 @@ k3s не входит в критический путь. Его можно ра Примеры стабильных операций: `POST /api/v1/searches`, `POST /api/v1/searches/{id}/refinements`, `POST /api/v1/candidates/{id}/invitations`, `POST /api/v1/invitations/{id}/accept`. Это целевые примеры, они пока не реализованы. Все бизнес-операции, ответы и ошибки должны входить в OpenAPI и иметь стабильные `operationId`. -Правила контракта: UUID для идентификаторов, UTC date-time, явные enums, целые рубли для MVP, ограниченная cursor pagination. Различать null и отсутствующее поле. Ошибка содержит стабильный `code`, безопасное сообщение, опциональные field errors и request ID. Idempotency keys нужны для создания invitation, запуска анализа и отправки assessment; ключ ограничен actor и операцией, повтор с другим телом отклоняется. Проверять доступ для каждого object ID, job, search run и PDF. Контакты не включаются в общие ошибки и публичные примеры. +Правила контракта: UUID для идентификаторов, UTC date-time, явные enums, целые рубли для MVP, ограниченная cursor pagination. Различать null и отсутствующее поле. Ошибка содержит стабильный `code`, безопасное сообщение, опциональные field errors и request ID. Idempotency keys нужны для создания invitation, запуска анализа и отправки assessment; ключ ограничен actor и операцией, повтор с другим телом отклоняется. Проверять доступ для каждого object ID, job, search run и PDF. Контакты не включаются в общие ошибки и публичные примеры. Модель ошибок, Idempotency-Key, If-Match, пагинация и формат времени закреплены в контракте, см. [api/README.md](../../api/README.md#соглашения-контракта); из них реализован только маппинг ошибок в problem. ## Метрики, телеметрия и alerts diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index ac158aa..b3824e3 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -112,6 +112,8 @@ make check не является бизнес-E2E проверкой. make verif Python-генератор datamodel-code-generator 0.83.0 читает api/ml/openapi.bundle.yml и создает ml/src/lincodex_ml/api/models.py. Настройки хранятся в ml/codegen/pyproject.toml; это конфигурация инструмента, а зависимости остаются в ml/pyproject.toml и uv.lock. Health/readiness handlers импортируют сгенерированные модели вместо ручных копий схем. make -C ml generate сначала собирает API; при вызове из корневого make generate параметр API_PREPARED=1 использует уже собранный bundle. make -C ml check-generated сравнивает результат через --check без перезаписи файла. CI использует общий make generate, который включает Python-модели. +Ошибки, повторы, версии, пагинация и время следуют [соглашениям контракта](../../api/README.md#соглашения-контракта). Реализовано: любая ошибка публичного Go API и ML-сервиса - problem по RFC 9457 (`application/problem+json`) со стабильным `code`. Go-маппинг ошибок ogen находится в backend/internal/adapter/primary/http/problem/: валидация запроса дает 400, неизвестный маршрут под /api - 404, нереализованная операция - 501, остальные ошибки и panic - 500 без внутреннего текста; ошибки логируются на этой границе, panic - только типом и stack. Frontend API client бросает `ApiRequestError` для problem, сетевых сбоев (`network_error`) и некорректных 2xx-тел (`invalid_response`); отмена вызывающим пробрасывается без изменений. ML-сервис преобразует ошибки FastAPI в ml/src/lincodex_ml/api/problems.py и направляет логи uvicorn через свой JSON-формат без текста исключений. Хранение Idempotency-Key, проверки If-Match и пагинация запланированы: контракт определяет их компоненты, а реализует их первая бизнес-операция, которой они нужны. + ## Код и слои Зависимости SQL-линтера перечислены в `backend/requirements-quality.txt` рядом с `.sqlfluff`. Команда `make -C backend lint-sql` устанавливает их в локальное окружение `.venv-quality` и проверяет миграции и запросы. Для запуска Go-сервиса это окружение не требуется. diff --git a/frontend/.gitignore b/frontend/.gitignore index f7b64fb..4563de8 100644 --- a/frontend/.gitignore +++ b/frontend/.gitignore @@ -13,3 +13,4 @@ test-results/ .env.* !.env.example *.log +.orval-compat-*/ diff --git a/frontend/.prettierignore b/frontend/.prettierignore index b232a17..52be24a 100644 --- a/frontend/.prettierignore +++ b/frontend/.prettierignore @@ -5,3 +5,4 @@ src/shared/api/endpoints/ src/shared/api/schemas/ scripts/fixtures/ pnpm-lock.yaml +.orval-compat-*/ diff --git a/frontend/Makefile b/frontend/Makefile index 69636bd..ac5eda3 100644 --- a/frontend/Makefile +++ b/frontend/Makefile @@ -1,5 +1,5 @@ .DEFAULT_GOAL := help -.PHONY: help install dev build generate fmt fmt-check lint lint-fix typecheck test check verify +.PHONY: help install dev build generate check-orval-compat fmt fmt-check lint lint-fix typecheck test check verify help: ## Show available frontend commands. @awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-12s %s\n", $$1, $$2}' $(MAKEFILE_LIST) @@ -17,6 +17,9 @@ generate: ## Generate API client, query hooks, schemas, and MSW handlers. @if [ "$${API_PREPARED:-0}" != "1" ]; then $(MAKE) -C ../api bundle; fi pnpm run generate +check-orval-compat: ## Generate and type-check the OpenAPI 3.2 compatibility fixture in a temporary directory. + pnpm run check:orval-compat + fmt: ## Format frontend source and configuration. pnpm run fmt diff --git a/frontend/README.en.md b/frontend/README.en.md index 551e62e..5f167d9 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -7,7 +7,7 @@ A React and TypeScript SPA built with Vite and organized using FSD. The current - `src/app/` starts the application; `pages/`, `widgets/`, `features/`, and `entities/` are the interface layers. - `src/shared/` contains shared components and the API client, including generated endpoints, Zod schemas, and MSW mocks. - `codegen/orval.config.ts` configures generation from the shared OpenAPI contract. -- `scripts/` checks FSD boundaries. +- `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture. From the repository root, `make -C frontend dev` starts development and `make -C frontend check` runs checks and builds the app. In Docker, Nginx serves the built files using configuration from `deploy/nginx/`. diff --git a/frontend/README.md b/frontend/README.md index 06c5cf3..d64e227 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -7,7 +7,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS - `src/app/` - запуск приложения; `pages/`, `widgets/`, `features/`, `entities/` - слои интерфейса. - `src/shared/` - общие компоненты и API-клиент, включая сгенерированные endpoints, схемы Zod и MSW-моки. - `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта. -- `scripts/` - проверки границ FSD. +- `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2. Из корня: `make -C frontend dev` запускает разработку, `make -C frontend check` - проверки и сборку. В Docker собранные файлы раздает Nginx с конфигурацией из `deploy/nginx/`. diff --git a/frontend/codegen/orval.config.ts b/frontend/codegen/orval.config.ts index 042d642..b1ad5cc 100644 --- a/frontend/codegen/orval.config.ts +++ b/frontend/codegen/orval.config.ts @@ -1,16 +1,70 @@ -import { defineConfig } from "orval"; +import { defineConfig, defineTransformer, type Options } from "orval"; -export default defineConfig({ - lincodex: { +const responseReferencePrefix = "#/components/responses/"; + +// Replaces each reference to components/responses with the referenced response +// object. Schema, header, and example references inside it stay references. +function inlineResponseReferences( + value: unknown, + responses: Readonly>, +): unknown { + if (Array.isArray(value)) { + return value.map((item) => inlineResponseReferences(item, responses)); + } + if (value === null || typeof value !== "object") { + return value; + } + + const reference = (value as { $ref?: unknown }).$ref; + if (typeof reference === "string" && reference.startsWith(responseReferencePrefix)) { + const name = reference.slice(responseReferencePrefix.length); + if (!Object.hasOwn(responses, name)) { + throw new Error(`Unknown response reference ${reference}.`); + } + return inlineResponseReferences(responses[name], responses); + } + + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [key, inlineResponseReferences(item, responses)]), + ); +} + +// Orval 8.40 writes no Zod schema for components/responses entries, yet an +// operation that references one imports a `Response` type that is never +// generated. Inlining the references keeps the contract's reusable responses +// while generated operations import only the component schemas Orval writes. +const inlineReusableResponses = defineTransformer((spec) => { + if (spec.paths === undefined) { + return spec; + } + const responses = spec.components?.responses ?? {}; + return { + ...spec, + paths: inlineResponseReferences(spec.paths, responses) as typeof spec.paths, + }; +}); + +// The API compatibility check sets this variable to a temporary directory to +// generate the OpenAPI 3.2 fixture with the production settings. +const compatOutput = process.env["ORVAL_COMPAT_OUTPUT"]; + +function project(inputTarget: string, endpoints: string, schemas: string): Options { + return { input: { - target: "../../api/core/openapi.bundle.yml", + target: inputTarget, + override: { + transformer: inlineReusableResponses, + }, }, output: { mode: "tags-split", - target: "../src/shared/api/endpoints", + target: endpoints, indexFiles: true, + // Generated operations take header parameters such as Idempotency-Key + // and If-Match as a typed argument instead of dropping them. + headers: true, schemas: { - path: "../src/shared/api/schemas", + path: schemas, type: "zod", splitByTags: true, }, @@ -31,7 +85,31 @@ export default defineConfig({ query: { signal: true, }, + // Optional properties are typed `{ x?: T }`, which the strict + // exactOptionalPropertyTypes setting needs for optional header + // parameters to fit RequestInit headers. + zod: { + exactOptional: true, + }, }, }, - }, -}); + }; +} + +export default defineConfig( + compatOutput === undefined + ? { + lincodex: project( + "../../api/core/openapi.bundle.yml", + "../src/shared/api/endpoints", + "../src/shared/api/schemas", + ), + } + : { + compat: project( + "../../api/testdata/openapi-3.2.0.yml", + `${compatOutput}/endpoints`, + `${compatOutput}/schemas`, + ), + }, +); diff --git a/frontend/package.json b/frontend/package.json index 518b37c..eca423f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -18,7 +18,8 @@ "test": "vitest run", "test:fsd": "node ./scripts/test-fsd-boundaries.mjs", "check": "pnpm run fmt:check && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run test:fsd && pnpm run build", - "verify": "pnpm run generate && pnpm run check" + "verify": "pnpm run generate && pnpm run check", + "check:orval-compat": "node ./scripts/check-orval-compat.mjs" }, "dependencies": { "@tanstack/react-query": "5.104.1", diff --git a/frontend/scripts/check-orval-compat.mjs b/frontend/scripts/check-orval-compat.mjs new file mode 100644 index 0000000..44fd642 --- /dev/null +++ b/frontend/scripts/check-orval-compat.mjs @@ -0,0 +1,72 @@ +// Generates the OpenAPI 3.2 compatibility fixture with the production Orval +// settings into a temporary directory, type-checks the output with the +// frontend compiler settings, and checks that the API conventions reached the +// generated code. The directory is removed afterwards. +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join, relative, resolve } from "node:path"; +import { env, stdout } from "node:process"; +import { fileURLToPath } from "node:url"; + +const frontendRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const bin = (name) => resolve(frontendRoot, "node_modules/.bin", name); + +// Text that each fixture convention leaves in the generated TypeScript. +const expectedFragments = { + IdempotencyKey: '"Idempotency-Key": zod.string().min(1).max(', + IfMatch: '"If-Match": zod.string().min(', + PageLimit: '"limit": zod.int().min(1).max(', + PageCursor: '"cursor": zod.string().min(1).max(', + PageInfo: '"next_cursor": zod.string().min(1).max(', + Timestamp: "export const Timestamp = zod.iso.datetime(", + Problem: "export const Problem = zod.object(", + ProblemErrorType: "TError = ErrorType", + HeaderArgument: "headers: CreateProbeItemHeaders", + OptionalHeaderArgument: "headers: UpdateProbeItemHeaders", +}; + +function run(command, args, extraEnv = {}) { + const result = spawnSync(command, args, { + cwd: frontendRoot, + encoding: "utf8", + env: { ...env, ...extraEnv }, + }); + assert.equal( + result.status, + 0, + `${relative(frontendRoot, command)} failed:\n${result.stdout}\n${result.stderr}`, + ); +} + +function typeScriptFiles(directory) { + return readdirSync(directory, { recursive: true, encoding: "utf8" }) + .filter((name) => name.endsWith(".ts")) + .map((name) => join(directory, name)); +} + +const outputDirectory = mkdtempSync(join(frontendRoot, ".orval-compat-")); +try { + run(bin("orval"), ["--config", "./codegen/orval.config.ts"], { + ORVAL_COMPAT_OUTPUT: outputDirectory, + }); + + const files = typeScriptFiles(outputDirectory); + assert.ok(files.length > 0, "Orval generated no files for the compatibility fixture."); + writeFileSync( + join(outputDirectory, "tsconfig.json"), + JSON.stringify({ + extends: "../tsconfig.json", + files: files.map((file) => relative(outputDirectory, file)), + }), + ); + run(bin("tsc"), ["--noEmit", "-p", outputDirectory]); + + const generated = files.map((file) => readFileSync(file, "utf8")).join("\n"); + for (const [component, fragment] of Object.entries(expectedFragments)) { + assert.ok(generated.includes(fragment), `Generated code lacks ${component}: ${fragment}`); + } + stdout.write(`Orval compatibility fixture: ${files.length} files type-checked.\n`); +} finally { + rmSync(outputDirectory, { recursive: true, force: true }); +} diff --git a/frontend/src/shared/api/client.test.ts b/frontend/src/shared/api/client.test.ts index bc43240..1b2c02c 100644 --- a/frontend/src/shared/api/client.test.ts +++ b/frontend/src/shared/api/client.test.ts @@ -1,7 +1,13 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, expectTypeOf, it, vi } from "vitest"; import { z } from "zod"; -import { apiRequest } from "./client"; -import { getHealthz } from "./endpoints/health/health"; +import { + ApiRequestError, + apiRequest, + invalidResponseCode, + networkErrorCode, + unknownErrorCode, +} from "./client"; +import { getHealthz, type GetHealthzQueryError } from "./endpoints/health/health"; const healthSchema = z.object({ status: z.literal("ok") }); @@ -53,31 +59,186 @@ describe("apiRequest", () => { }); }); - it("maps structured HTTP errors to a stable error type", async () => { + it("maps an RFC 9457 problem response to ApiRequestError", async () => { const request = vi.fn().mockResolvedValue( new Response( JSON.stringify({ - code: "service_unavailable", - message: "Service unavailable", - request_id: "req-test", + type: "urn:lincodex:problem:validation_failed", + title: "Request validation failed", + status: 400, + code: "validation_failed", + detail: "One or more request fields are invalid.", + trace_id: "0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10", + errors: [ + { + in: "query", + pointer: "/limit", + code: "invalid", + message: "The value does not match the contract.", + }, + ], }), { - status: 503, - headers: { "content-type": "application/json" }, + status: 400, + headers: { "content-type": "application/problem+json" }, + }, + ), + ); + vi.stubGlobal("fetch", request); + + const error: unknown = await apiRequest("/healthz").catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ApiRequestError); + expect(error).toMatchObject({ + name: "ApiRequestError", + message: "One or more request fields are invalid.", + status: 400, + code: "validation_failed", + title: "Request validation failed", + detail: "One or more request fields are invalid.", + traceId: "0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10", + fieldErrors: [ + { + in: "query", + pointer: "/limit", + code: "invalid", + message: "The value does not match the contract.", + }, + ], + }); + }); + + it("uses the title and the request ID header when the problem omits them", async () => { + const request = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + type: "urn:lincodex:problem:forbidden", + title: "Access denied", + status: 403, + code: "forbidden", + }), + { + status: 403, + headers: { + "content-type": "application/problem+json; charset=utf-8", + "x-request-id": "req-403", + }, }, ), ); vi.stubGlobal("fetch", request); await expect(apiRequest("/healthz")).rejects.toMatchObject({ - name: "ApiRequestError", - message: "Service unavailable", - status: 503, - code: "service_unavailable", - requestId: "req-test", + message: "Access denied", + status: 403, + code: "forbidden", + detail: undefined, + traceId: "req-403", + fieldErrors: [], }); }); + it.each([ + { + name: "a JSON body that is not a problem", + body: JSON.stringify({ code: "service_unavailable", message: "Service unavailable" }), + contentType: "application/json", + }, + { + name: "a problem with an unknown code", + body: JSON.stringify({ + type: "urn:lincodex:problem:new", + title: "New", + status: 503, + code: "new", + }), + contentType: "application/problem+json", + }, + { name: "a proxy error page", body: "Bad gateway", contentType: "text/html" }, + ])("falls back to http_error for $name", async ({ body, contentType }) => { + const request = vi.fn().mockResolvedValue( + new Response(body, { + status: 503, + headers: { "content-type": contentType, "x-request-id": "req-503" }, + }), + ); + vi.stubGlobal("fetch", request); + + await expect(apiRequest("/healthz")).rejects.toMatchObject({ + name: "ApiRequestError", + message: "Request failed with status 503.", + status: 503, + code: unknownErrorCode, + traceId: "req-503", + fieldErrors: [], + }); + }); + + it("maps a network failure to ApiRequestError with status 0", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch"))); + + const error: unknown = await apiRequest("/healthz").catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ApiRequestError); + expect(error).toMatchObject({ status: 0, code: networkErrorCode, fieldErrors: [] }); + }); + + it("lets a cancellation by the caller propagate unchanged", async () => { + const controller = new AbortController(); + const abortError = new DOMException("The operation was aborted.", "AbortError"); + vi.stubGlobal( + "fetch", + vi.fn().mockImplementation(() => { + controller.abort(abortError); + return Promise.reject(abortError); + }), + ); + + await expect(apiRequest("/healthz", { signal: controller.signal })).rejects.toBe(abortError); + }); + + it.each([ + { + name: "a body that is not JSON", + body: "ok", + schema: healthSchema, + }, + { + name: "a body that does not match the response schema", + body: JSON.stringify({ status: "degraded" }), + schema: healthSchema, + }, + ])("maps a 2xx response with $name to invalid_response", async ({ body, schema }) => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + new Response(body, { + status: 200, + headers: { "content-type": "application/json", "x-request-id": "req-200" }, + }), + ), + ); + + const error: unknown = await apiRequest("/healthz", {}, schema).catch( + (caught: unknown) => caught, + ); + + expect(error).toBeInstanceOf(ApiRequestError); + expect(error).toMatchObject({ status: 200, code: invalidResponseCode, traceId: "req-200" }); + }); + + it("reports a cross-origin path as a programming error before any request", async () => { + const request = vi.fn(); + vi.stubGlobal("fetch", request); + + await expect(apiRequest("https://example.com/api/v1/healthz")).rejects.toThrow(TypeError); + expect(request).not.toHaveBeenCalled(); + }); + + it("types generated query errors as ApiRequestError", () => { + expectTypeOf().toEqualTypeOf(); + }); + it("rejects an already-prefixed path before making a request", async () => { const request = vi.fn(); vi.stubGlobal("fetch", request); diff --git a/frontend/src/shared/api/client.ts b/frontend/src/shared/api/client.ts index 311c74d..f4a62a2 100644 --- a/frontend/src/shared/api/client.ts +++ b/frontend/src/shared/api/client.ts @@ -1,28 +1,73 @@ -import { z } from "zod"; +import type { z } from "zod"; +import { Problem, type ProblemCode, type ProblemFieldError } from "./schemas"; const apiPrefix = "/api/v1"; const localOrigin = "http://lincodex.local"; +const problemMediaType = "application/problem+json"; +const requestIdHeader = "X-Request-ID"; -const errorEnvelopeSchema = z - .object({ - code: z.string().optional(), - message: z.string().optional(), - request_id: z.string().optional(), - }) - .passthrough(); +/** Code used when an error response is not a contract problem document. */ +export const unknownErrorCode = "http_error"; +/** Code used when the request did not produce an HTTP response. */ +export const networkErrorCode = "network_error"; +/** Code used when a 2xx response body is not valid JSON or does not match its schema. */ +export const invalidResponseCode = "invalid_response"; +/** + * Contract problem codes plus client-side codes that never appear in a + * server response. + */ +export type ApiErrorCode = + ProblemCode | typeof unknownErrorCode | typeof networkErrorCode | typeof invalidResponseCode; + +type ApiRequestErrorInit = { + status: number; + code: ApiErrorCode; + title: string; + detail?: string | undefined; + traceId?: string | undefined; + fieldErrors?: readonly ProblemFieldError[] | undefined; +}; + +/** + * Error for every failed API request. For RFC 9457 problem responses it + * carries the contract fields. `status` is 0 when no HTTP response arrived. + */ export class ApiRequestError extends Error { - constructor( - message: string, - readonly status: number, - readonly code: string, - readonly requestId: string | undefined, - ) { - super(message); + readonly status: number; + readonly code: ApiErrorCode; + readonly title: string; + readonly detail: string | undefined; + readonly traceId: string | undefined; + readonly fieldErrors: readonly ProblemFieldError[]; + + constructor(init: ApiRequestErrorInit) { + super(init.detail ?? init.title); this.name = "ApiRequestError"; + this.status = init.status; + this.code = init.code; + this.title = init.title; + this.detail = init.detail; + this.traceId = init.traceId; + this.fieldErrors = init.fieldErrors ?? []; } } +/** + * Error type of generated query hooks. Orval passes the contract error schema + * as the argument; the conditional only consumes it. + * + * apiRequest rejects with ApiRequestError for every request failure: an error + * response, a network failure, and a 2xx body that is not valid JSON or does + * not match its schema. It rejects with another error in two cases that are + * not request failures: when the caller's AbortSignal cancels the request, + * the original abort error propagates unchanged (TanStack Query treats it as + * cancellation, not as a query error); and when a generated path is not a + * same-origin /api/v1 path, a TypeError reports the programming error before + * any request is sent. + */ +export type ErrorType = ContractError extends unknown ? ApiRequestError : never; + function buildApiUrl(path: string): string { const parsed = new URL(path, localOrigin); if (parsed.origin !== localOrigin) { @@ -40,25 +85,49 @@ function buildApiUrl(path: string): string { return `${pathname}${parsed.search}`; } -async function toApiError(response: Response): Promise { - const body: unknown = await response.json().catch(() => undefined); - const parsed = errorEnvelopeSchema.safeParse(body); +function isAbort(error: unknown, signal: AbortSignal | null | undefined): boolean { + return signal?.aborted === true || (error instanceof DOMException && error.name === "AbortError"); +} - if (parsed.success) { - return new ApiRequestError( - parsed.data.message ?? `Request failed with status ${response.status}.`, - response.status, - parsed.data.code ?? "http_error", - parsed.data.request_id, - ); +function isProblemResponse(response: Response): boolean { + const mediaType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase(); + return mediaType === problemMediaType; +} + +async function toApiError(response: Response): Promise { + const headerTraceId = response.headers.get(requestIdHeader) ?? undefined; + + if (isProblemResponse(response)) { + const body: unknown = await response.json().catch(() => undefined); + const parsed = Problem.safeParse(body); + if (parsed.success) { + const problem = parsed.data; + return new ApiRequestError({ + status: response.status, + code: problem.code, + title: problem.title, + detail: problem.detail, + traceId: problem.trace_id ?? headerTraceId, + fieldErrors: problem.errors, + }); + } } - return new ApiRequestError( - `Request failed with status ${response.status}.`, - response.status, - "http_error", - undefined, - ); + return new ApiRequestError({ + status: response.status, + code: unknownErrorCode, + title: `Request failed with status ${response.status}.`, + traceId: headerTraceId, + }); +} + +function invalidResponseError(response: Response): ApiRequestError { + return new ApiRequestError({ + status: response.status, + code: invalidResponseCode, + title: "The response does not match the API contract.", + traceId: response.headers.get(requestIdHeader) ?? undefined, + }); } export async function apiRequest( @@ -66,15 +135,41 @@ export async function apiRequest( init: RequestInit = {}, responseSchema?: z.ZodType, ): Promise { - const response = await fetch(buildApiUrl(path), { - ...init, - credentials: "include", - }); + const url = buildApiUrl(path); + + let response: Response; + try { + response = await fetch(url, { ...init, credentials: "include" }); + } catch (error: unknown) { + if (isAbort(error, init.signal)) { + throw error; + } + throw new ApiRequestError({ + status: 0, + code: networkErrorCode, + title: "The request did not reach the server.", + }); + } if (!response.ok) { throw await toApiError(response); } - const body: unknown = response.status === 204 ? undefined : await response.json(); - return responseSchema ? responseSchema.parse(body) : (body as T); + let body: unknown; + try { + body = response.status === 204 ? undefined : await response.json(); + } catch (error: unknown) { + if (isAbort(error, init.signal)) { + throw error; + } + throw invalidResponseError(response); + } + if (!responseSchema) { + return body as T; + } + const parsed = responseSchema.safeParse(body); + if (!parsed.success) { + throw invalidResponseError(response); + } + return parsed.data; } diff --git a/frontend/src/shared/api/endpoints/health/health.ts b/frontend/src/shared/api/endpoints/health/health.ts index 87b4bad..69e6b1b 100644 --- a/frontend/src/shared/api/endpoints/health/health.ts +++ b/frontend/src/shared/api/endpoints/health/health.ts @@ -20,10 +20,12 @@ import type { } from '@tanstack/react-query'; import type { - HealthResponse + HealthResponse, + Problem } from '../../schemas'; import { apiRequest } from '../../client'; +import type { ErrorType } from '../../client'; type SecondParameter unknown> = Parameters[1]; @@ -78,7 +80,7 @@ export const getGetHealthzQueryKey = () => { } -export const getGetHealthzQueryOptions = >, TError = unknown>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +export const getGetHealthzQueryOptions = >, TError = ErrorType>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} ) => { const {query: queryOptions, request: requestOptions} = options ?? {}; @@ -97,10 +99,10 @@ const {query: queryOptions, request: requestOptions} = options ?? {}; } export type GetHealthzQueryResult = NonNullable>> -export type GetHealthzQueryError = unknown +export type GetHealthzQueryError = ErrorType -export function useGetHealthz>, TError = unknown>( +export function useGetHealthz>, TError = ErrorType>( options: { query:Partial>, TError, TData>> & Pick< DefinedInitialDataOptions< Awaited>, @@ -110,7 +112,7 @@ export function useGetHealthz>, TE >, request?: SecondParameter} , queryClient?: QueryClient ): DefinedUseQueryResult & { queryKey: DataTag } -export function useGetHealthz>, TError = unknown>( +export function useGetHealthz>, TError = ErrorType>( options?: { query?:Partial>, TError, TData>> & Pick< UndefinedInitialDataOptions< Awaited>, @@ -120,7 +122,7 @@ export function useGetHealthz>, TE >, request?: SecondParameter} , queryClient?: QueryClient ): UseQueryResult & { queryKey: DataTag } -export function useGetHealthz>, TError = unknown>( +export function useGetHealthz>, TError = ErrorType>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} , queryClient?: QueryClient ): UseQueryResult & { queryKey: DataTag } @@ -128,7 +130,7 @@ export function useGetHealthz>, TE * @summary Check whether the API process is responding. */ -export function useGetHealthz>, TError = unknown>( +export function useGetHealthz>, TError = ErrorType>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} , queryClient?: QueryClient ): UseQueryResult & { queryKey: DataTag } { diff --git a/frontend/src/shared/api/index.ts b/frontend/src/shared/api/index.ts index e3554dc..cbb50d2 100644 --- a/frontend/src/shared/api/index.ts +++ b/frontend/src/shared/api/index.ts @@ -1 +1,8 @@ -export { ApiRequestError, apiRequest } from "./client"; +export { + ApiRequestError, + apiRequest, + invalidResponseCode, + networkErrorCode, + unknownErrorCode, + type ApiErrorCode, +} from "./client"; diff --git a/frontend/src/shared/api/schemas/health/index.ts b/frontend/src/shared/api/schemas/health/index.ts index ae7e418..39932a5 100644 --- a/frontend/src/shared/api/schemas/health/index.ts +++ b/frontend/src/shared/api/schemas/health/index.ts @@ -6,3 +6,7 @@ */ export * from './healthResponse.zod'; +export * from './problem.zod'; +export * from './problemCode.zod'; +export * from './problemFieldError.zod'; +export * from './problemFieldLocation.zod'; diff --git a/frontend/src/shared/api/schemas/health/problem.zod.ts b/frontend/src/shared/api/schemas/health/problem.zod.ts new file mode 100644 index 0000000..9e09c18 --- /dev/null +++ b/frontend/src/shared/api/schemas/health/problem.zod.ts @@ -0,0 +1,54 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const problemTypeMax = 256; + +export const problemTitleMax = 200; + +export const problemStatusMin = 400; +export const problemStatusMax = 599; + +export const problemDetailMax = 1000; + +export const problemInstanceMax = 2048; + +export const problemTraceIdMax = 128; + + +export const problemTraceIdRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const problemErrorsItemPointerMax = 1024; + + +export const problemErrorsItemPointerRegExp = new RegExp('^(/([^~/]|~[01])*)*$'); +export const problemErrorsItemCodeMax = 64; + + +export const problemErrorsItemCodeRegExp = new RegExp('^[a-z][a-z0-9_]*$'); +export const problemErrorsItemMessageMax = 500; + +export const problemErrorsMax = 100; + + +export const Problem = zod.object({ + "type": zod.string().max(problemTypeMax).describe('URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference.'), + "title": zod.string().min(1).max(problemTitleMax).describe('Short, fixed English summary of the problem type. It does not change between occurrences.'), + "status": zod.int().min(problemStatusMin).max(problemStatusMax).describe('HTTP status code generated by the origin server.'), + "code": zod.enum(['validation_failed', 'unauthenticated', 'forbidden', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.'), + "detail": zod.string().max(problemDetailMax).exactOptional().describe('Safe English explanation of this occurrence. It never contains internal error text or request values.'), + "instance": zod.string().max(problemInstanceMax).exactOptional().describe('URI reference that identifies this occurrence, when one exists.'), + "trace_id": zod.string().min(1).max(problemTraceIdMax).regex(problemTraceIdRegExp).exactOptional().describe('Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; it is not a secret.'), + "errors": zod.array(zod.object({ + "in": zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.'), + "pointer": zod.string().max(problemErrorsItemPointerMax).regex(problemErrorsItemPointerRegExp).describe('JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.'), + "code": zod.string().min(1).max(problemErrorsItemCodeMax).regex(problemErrorsItemCodeRegExp).describe('Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.'), + "message": zod.string().min(1).max(problemErrorsItemMessageMax).describe('Fixed English message that never echoes the submitted value.') +}).describe('One reason why a request field or parameter is invalid.')).max(problemErrorsMax).exactOptional().describe('Field-level reasons for validation_failed. Other codes omit it.') +}).describe('Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.') + +export type Problem = zod.input; +export type ProblemOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/health/problemCode.zod.ts b/frontend/src/shared/api/schemas/health/problemCode.zod.ts new file mode 100644 index 0000000..90d890b --- /dev/null +++ b/frontend/src/shared/api/schemas/health/problemCode.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const ProblemCode = zod.enum(['validation_failed', 'unauthenticated', 'forbidden', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.') + +export type ProblemCode = zod.input; +export type ProblemCodeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/health/problemFieldError.zod.ts b/frontend/src/shared/api/schemas/health/problemFieldError.zod.ts new file mode 100644 index 0000000..a6afab6 --- /dev/null +++ b/frontend/src/shared/api/schemas/health/problemFieldError.zod.ts @@ -0,0 +1,28 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const problemFieldErrorPointerMax = 1024; + + +export const problemFieldErrorPointerRegExp = new RegExp('^(/([^~/]|~[01])*)*$'); +export const problemFieldErrorCodeMax = 64; + + +export const problemFieldErrorCodeRegExp = new RegExp('^[a-z][a-z0-9_]*$'); +export const problemFieldErrorMessageMax = 500; + + +export const ProblemFieldError = zod.object({ + "in": zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.'), + "pointer": zod.string().max(problemFieldErrorPointerMax).regex(problemFieldErrorPointerRegExp).describe('JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.'), + "code": zod.string().min(1).max(problemFieldErrorCodeMax).regex(problemFieldErrorCodeRegExp).describe('Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.'), + "message": zod.string().min(1).max(problemFieldErrorMessageMax).describe('Fixed English message that never echoes the submitted value.') +}).describe('One reason why a request field or parameter is invalid.') + +export type ProblemFieldError = zod.input; +export type ProblemFieldErrorOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/health/problemFieldLocation.zod.ts b/frontend/src/shared/api/schemas/health/problemFieldLocation.zod.ts new file mode 100644 index 0000000..488db8d --- /dev/null +++ b/frontend/src/shared/api/schemas/health/problemFieldLocation.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const ProblemFieldLocation = zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.') + +export type ProblemFieldLocation = zod.input; +export type ProblemFieldLocationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/index.ts b/frontend/src/shared/api/schemas/index.ts index e5b4849..6d1eb71 100644 --- a/frontend/src/shared/api/schemas/index.ts +++ b/frontend/src/shared/api/schemas/index.ts @@ -5,4 +5,6 @@ * OpenAPI spec version: 0.1.0 */ +export * from './pageInfo.zod'; +export * from './timestamp.zod'; export * from './health'; diff --git a/frontend/src/shared/api/schemas/pageInfo.zod.ts b/frontend/src/shared/api/schemas/pageInfo.zod.ts new file mode 100644 index 0000000..ec6905c --- /dev/null +++ b/frontend/src/shared/api/schemas/pageInfo.zod.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const pageInfoNextCursorMax = 512; + + +export const pageInfoNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const PageInfo = zod.object({ + "has_more": zod.boolean().describe('Whether another page follows this one.'), + "next_cursor": zod.string().min(1).max(pageInfoNextCursorMax).regex(pageInfoNextCursorRegExp).nullable().describe('Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.') +}).describe('Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.') + +export type PageInfo = zod.input; +export type PageInfoOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/timestamp.zod.ts b/frontend/src/shared/api/schemas/timestamp.zod.ts new file mode 100644 index 0000000..e961b99 --- /dev/null +++ b/frontend/src/shared/api/schemas/timestamp.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const Timestamp = zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') + +export type Timestamp = zod.input; +export type TimestampOutput = zod.output; diff --git a/ml/Makefile b/ml/Makefile index 9f73d8b..a8ca3e2 100644 --- a/ml/Makefile +++ b/ml/Makefile @@ -1,7 +1,7 @@ .DEFAULT_GOAL := help UV ?= uv API_PREPARED ?= 0 -.PHONY: help install generate check-generated build run fmt fmt-check lint lint-fix typecheck test test-contract check verify +.PHONY: help install generate check-generated check-pydantic-compat build run fmt fmt-check lint lint-fix typecheck test test-contract check verify help: ## Show available ML service commands. @awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-14s %s\n", $$1, $$2}' $(MAKEFILE_LIST) @@ -16,6 +16,12 @@ generate: ## Generate Pydantic models from the shared ML contract. check-generated: ## Check Pydantic models against the bundled contract without rewriting them. cd codegen && $(UV) run --project .. datamodel-codegen --check +check-pydantic-compat: ## Generate Pydantic models from the OpenAPI 3.2 compatibility fixture into a temporary directory and check them. + @temporary_dir=$$(mktemp -d) && trap 'rm -rf "$$temporary_dir"' EXIT && \ + (cd codegen && $(UV) run --project .. datamodel-codegen --input ../../api/testdata/openapi-3.2.0.yml --output "$$temporary_dir/fixture_models.py" --openapi-scopes schemas parameters paths) && \ + $(UV) run mypy --strict "$$temporary_dir/fixture_models.py" && \ + $(UV) run python scripts/check_fixture_models.py "$$temporary_dir/fixture_models.py" + build: ## Build the service wheel. $(UV) build @@ -23,16 +29,16 @@ run: ## Run the operational API on port 8000. $(UV) run uvicorn lincodex_ml.main:app --host 0.0.0.0 --port 8000 fmt: ## Format Python source. - $(UV) run ruff format src tests + $(UV) run ruff format src tests scripts fmt-check: ## Check Python formatting. - $(UV) run ruff format --check src tests + $(UV) run ruff format --check src tests scripts lint: ## Run Ruff checks. - $(UV) run ruff check src tests + $(UV) run ruff check src tests scripts lint-fix: ## Apply safe Ruff fixes. - $(UV) run ruff check --fix src tests + $(UV) run ruff check --fix src tests scripts typecheck: ## Run strict mypy checks. $(UV) run mypy src diff --git a/ml/README.en.md b/ml/README.en.md index 8291775..1e1a0bd 100644 --- a/ml/README.en.md +++ b/ml/README.en.md @@ -7,6 +7,7 @@ A separate Python service using FastAPI for future resume analysis and candidate - `src/lincodex_ml/` contains the application, HTTP routes, and infrastructure code. - `codegen/` configures Pydantic model generation from `api/ml/`. - `tests/` checks service health and contract conformance. +- `scripts/` checks Pydantic models generated from the OpenAPI 3.2 fixture. - `pyproject.toml` and `uv.lock` define dependencies and Python tool settings. From the repository root, `make -C ml check` runs checks and `make -C ml run` starts the service locally. To use its separate Compose project, run `make -C deploy ml-up` after preparing `.env`. diff --git a/ml/README.md b/ml/README.md index 48bf8eb..a61d547 100644 --- a/ml/README.md +++ b/ml/README.md @@ -7,6 +7,7 @@ - `src/lincodex_ml/` - приложение, HTTP-маршруты и инфраструктурный код. - `codegen/` - настройки генерации моделей Pydantic из `api/ml/`. - `tests/` - проверки состояния сервиса и соответствия контракту. +- `scripts/` - проверка Pydantic-моделей, сгенерированных из фикстуры OpenAPI 3.2. - `pyproject.toml` и `uv.lock` - зависимости и настройки Python-инструментов. Из корня: `make -C ml check` запускает проверки, `make -C ml run` - сервис локально. Для запуска через отдельный Compose используйте `make -C deploy ml-up` после подготовки `.env`. diff --git a/ml/codegen/pyproject.toml b/ml/codegen/pyproject.toml index 4013993..b3eb55b 100644 --- a/ml/codegen/pyproject.toml +++ b/ml/codegen/pyproject.toml @@ -8,3 +8,5 @@ openapi-scopes = ["schemas"] enum-field-as-literal = "all" disable-timestamp = true formatters = ["ruff-check", "ruff-format"] +field-constraints = true +use-annotated = true diff --git a/ml/scripts/check_fixture_models.py b/ml/scripts/check_fixture_models.py new file mode 100644 index 0000000..5b84f54 --- /dev/null +++ b/ml/scripts/check_fixture_models.py @@ -0,0 +1,86 @@ +"""Validate Pydantic models generated from the OpenAPI 3.2 compatibility fixture. + +make check-pydantic-compat generates the models into a temporary file and +passes its path. The checks cover the api/core conventions that +datamodel-code-generator turns into models: Problem, PageInfo, Timestamp, and +the PageLimit and PageCursor query parameters. It does not generate header +parameters or response headers, so Idempotency-Key, If-Match, and ETag have no +model to check. +""" + +import importlib.util +import sys +from pathlib import Path +from types import ModuleType + +from pydantic import BaseModel, ValidationError + + +def load(path: Path) -> ModuleType: + spec = importlib.util.spec_from_file_location("fixture_models", path) + if spec is None or spec.loader is None: + raise SystemExit(f"cannot load generated models from {path}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def rejects(model: type[BaseModel], payload: object) -> bool: + try: + model.model_validate(payload) + except ValidationError: + return True + return False + + +def main(path: Path) -> None: + models = load(path) + + problem = models.Problem.model_validate( + { + "type": "urn:lincodex:problem:state_conflict", + "title": "Resource state conflict", + "status": 409, + "code": "state_conflict", + "errors": [{"in": "body", "pointer": "/name", "code": "invalid", "message": "m"}], + } + ) + assert problem.code.root == "state_conflict" + assert rejects(models.Problem, {"type": "t", "title": "t", "status": 409, "code": "unknown"}) + assert rejects(models.Problem, {"type": "t", "title": "t", "status": 200, "code": "internal"}) + + page = models.PageInfo.model_validate({"has_more": False, "next_cursor": None}) + assert page.next_cursor is None + assert rejects(models.PageInfo, {"has_more": False}) + assert rejects(models.PageInfo, {"has_more": True, "next_cursor": "a" * 513}) + + stamp = models.Timestamp.model_validate("2026-10-05T09:30:00Z") + assert models.Timestamp(stamp.root).model_dump_json() == '"2026-10-05T09:30:00Z"' + assert rejects(models.Timestamp, "2026-10-05T09:30:00") + + query = models.ProbeItemsGetParametersQuery.model_validate({}) + assert query.limit == 20 + assert rejects(models.ProbeItemsGetParametersQuery, {"limit": 0}) + assert rejects(models.ProbeItemsGetParametersQuery, {"limit": 101}) + assert rejects(models.ProbeItemsGetParametersQuery, {"cursor": "a b"}) + + item_page = models.ProbeItemPage.model_validate( + { + "items": [ + { + "id": "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11", + "name": "probe", + "updated_at": "2026-10-05T09:30:00Z", + } + ], + "page": {"has_more": False, "next_cursor": None}, + } + ) + assert len(item_page.items) == 1 + print("Pydantic compatibility fixture: generated models validated.") + + +if __name__ == "__main__": + if len(sys.argv) != 2: + raise SystemExit("usage: check_fixture_models.py ") + main(Path(sys.argv[1])) diff --git a/ml/src/lincodex_ml/api/models.py b/ml/src/lincodex_ml/api/models.py index 14c18d8..c8f7590 100644 --- a/ml/src/lincodex_ml/api/models.py +++ b/ml/src/lincodex_ml/api/models.py @@ -1,9 +1,148 @@ # generated by datamodel-codegen: # filename: openapi.bundle.yml -from typing import Literal +from typing import Annotated, Literal -from pydantic import BaseModel, ConfigDict +from pydantic import BaseModel, ConfigDict, Field, RootModel + + +class ProblemCode( + RootModel[ + Literal[ + "validation_failed", + "unauthenticated", + "forbidden", + "not_found", + "method_not_allowed", + "idempotency_in_progress", + "state_conflict", + "version_conflict", + "payload_too_large", + "unsupported_media_type", + "idempotency_key_reused", + "precondition_required", + "rate_limited", + "internal", + "not_implemented", + ] + ] +): + root: Annotated[ + Literal[ + "validation_failed", + "unauthenticated", + "forbidden", + "not_found", + "method_not_allowed", + "idempotency_in_progress", + "state_conflict", + "version_conflict", + "payload_too_large", + "unsupported_media_type", + "idempotency_key_reused", + "precondition_required", + "rate_limited", + "internal", + "not_implemented", + ], + Field( + description="Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet." + ), + ] + + +class ProblemFieldLocation(RootModel[Literal["body", "query", "path", "header", "cookie"]]): + root: Annotated[ + Literal["body", "query", "path", "header", "cookie"], + Field(description="Part of the request that contains the invalid field."), + ] + + +class ProblemFieldError(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + in_: Annotated[ProblemFieldLocation, Field(alias="in")] + pointer: Annotated[ + str, + Field( + description="JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.", + max_length=1024, + pattern="^(/([^~/]|~[01])*)*$", + ), + ] + code: Annotated[ + str, + Field( + description="Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.", + max_length=64, + min_length=1, + pattern="^[a-z][a-z0-9_]*$", + ), + ] + message: Annotated[ + str, + Field( + description="Fixed English message that never echoes the submitted value.", + max_length=500, + min_length=1, + ), + ] + + +class Problem(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + type: Annotated[ + str, + Field( + description="URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference.", + max_length=256, + ), + ] + title: Annotated[ + str, + Field( + description="Short, fixed English summary of the problem type. It does not change between occurrences.", + max_length=200, + min_length=1, + ), + ] + status: Annotated[ + int, Field(description="HTTP status code generated by the origin server.", ge=400, le=599) + ] + code: ProblemCode + detail: Annotated[ + str | None, + Field( + description="Safe English explanation of this occurrence. It never contains internal error text or request values.", + max_length=1000, + ), + ] = None + instance: Annotated[ + str | None, + Field( + description="URI reference that identifies this occurrence, when one exists.", + max_length=2048, + ), + ] = None + trace_id: Annotated[ + str | None, + Field( + description="Request identifier of the call when the caller propagated one; it is not a secret.", + max_length=128, + min_length=1, + pattern="^[A-Za-z0-9._-]+$", + ), + ] = None + errors: Annotated[ + list[ProblemFieldError] | None, + Field( + description="Field-level reasons for validation_failed. Other codes omit it.", + max_length=100, + ), + ] = None class MLHealthResponse(BaseModel): diff --git a/ml/src/lincodex_ml/api/problems.py b/ml/src/lincodex_ml/api/problems.py new file mode 100644 index 0000000..90a5830 --- /dev/null +++ b/ml/src/lincodex_ml/api/problems.py @@ -0,0 +1,281 @@ +"""RFC 9457 problem responses that match the shared ML contract.""" + +import logging +import re +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Final + +from fastapi import FastAPI, Request, status +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from starlette.exceptions import HTTPException as StarletteHTTPException +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +from lincodex_ml.api.models import Problem, ProblemCode, ProblemFieldError, ProblemFieldLocation + +PROBLEM_MEDIA_TYPE: Final = "application/problem+json" + +_TYPE_PREFIX: Final = "urn:lincodex:problem:" +_REQUEST_ID_HEADER: Final = "X-Request-ID" +_REQUEST_ID_PATTERN: Final = re.compile(r"[A-Za-z0-9._-]{1,128}") +# Matches the maxItems bound of Problem.errors. +_MAX_FIELD_ERRORS: Final = 100 +_FIELD_CODE_REQUIRED: Final = "required" +_FIELD_CODE_INVALID: Final = "invalid" +_FIELD_MESSAGES: Final = { + _FIELD_CODE_REQUIRED: "The value is required.", + _FIELD_CODE_INVALID: "The value does not match the contract.", +} +_FIELD_LOCATIONS: Final = frozenset({"body", "query", "path", "header", "cookie"}) + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True, slots=True) +class _Definition: + code: ProblemCode + status: int + title: str + detail: str + + +_VALIDATION_FAILED: Final = _Definition( + ProblemCode("validation_failed"), + status.HTTP_400_BAD_REQUEST, + "Request validation failed", + "One or more request fields are invalid.", +) +_INTERNAL: Final = _Definition( + ProblemCode("internal"), + status.HTTP_500_INTERNAL_SERVER_ERROR, + "Internal server error", + "The server could not complete the request.", +) + +# Problem for each HTTP status that has a contract code. FastAPI reports body +# validation as 422, which the contract answers as 400 validation_failed; 422 +# idempotency_key_reused belongs to the public API and has no ML use. +_STATUS_DEFINITIONS: Final[Mapping[int, _Definition]] = { + status.HTTP_400_BAD_REQUEST: _VALIDATION_FAILED, + status.HTTP_401_UNAUTHORIZED: _Definition( + ProblemCode("unauthenticated"), + status.HTTP_401_UNAUTHORIZED, + "Authentication required", + "Sign in and repeat the request.", + ), + status.HTTP_403_FORBIDDEN: _Definition( + ProblemCode("forbidden"), + status.HTTP_403_FORBIDDEN, + "Access denied", + "You do not have permission to perform this operation.", + ), + status.HTTP_404_NOT_FOUND: _Definition( + ProblemCode("not_found"), + status.HTTP_404_NOT_FOUND, + "Resource not found", + "The requested resource does not exist.", + ), + status.HTTP_405_METHOD_NOT_ALLOWED: _Definition( + ProblemCode("method_not_allowed"), + status.HTTP_405_METHOD_NOT_ALLOWED, + "Method not allowed", + "The resource does not support this method; see the Allow header.", + ), + status.HTTP_409_CONFLICT: _Definition( + ProblemCode("state_conflict"), + status.HTTP_409_CONFLICT, + "Resource state conflict", + "The resource is in a state that does not allow this operation.", + ), + status.HTTP_412_PRECONDITION_FAILED: _Definition( + ProblemCode("version_conflict"), + status.HTTP_412_PRECONDITION_FAILED, + "Resource version conflict", + "The resource changed after it was read. Read it again before retrying.", + ), + status.HTTP_413_CONTENT_TOO_LARGE: _Definition( + ProblemCode("payload_too_large"), + status.HTTP_413_CONTENT_TOO_LARGE, + "Request body too large", + "Reduce the request body size and retry.", + ), + status.HTTP_415_UNSUPPORTED_MEDIA_TYPE: _Definition( + ProblemCode("unsupported_media_type"), + status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, + "Unsupported media type", + "Send the request body with a media type that the operation accepts.", + ), + status.HTTP_422_UNPROCESSABLE_CONTENT: _VALIDATION_FAILED, + status.HTTP_428_PRECONDITION_REQUIRED: _Definition( + ProblemCode("precondition_required"), + status.HTTP_428_PRECONDITION_REQUIRED, + "Precondition required", + "Send If-Match with the ETag of the version you read.", + ), + status.HTTP_429_TOO_MANY_REQUESTS: _Definition( + ProblemCode("rate_limited"), + status.HTTP_429_TOO_MANY_REQUESTS, + "Too many requests", + "Wait for the Retry-After interval and retry.", + ), + status.HTTP_501_NOT_IMPLEMENTED: _Definition( + ProblemCode("not_implemented"), + status.HTTP_501_NOT_IMPLEMENTED, + "Operation not implemented", + "This operation is not available yet.", + ), +} +# Response headers of an HTTP exception that a problem response keeps. +_FORWARDED_HEADERS: Final = ("Allow", "Retry-After") + + +def install_problem_handlers(application: FastAPI) -> None: + """Answer every framework and unhandled error with a problem response.""" + application.add_exception_handler(RequestValidationError, _handle_validation_error) + application.add_exception_handler(StarletteHTTPException, _handle_http_exception) + application.add_middleware(UnhandledErrorMiddleware) + + +def _definition_for_status(status_code: int) -> _Definition: + """Return the problem for an HTTP status raised inside the service. + + A status without a contract code is still a client error when it is 4xx and + becomes 400 validation_failed; every other unmapped status is internal. + """ + definition = _STATUS_DEFINITIONS.get(status_code) + if definition is not None: + return definition + if status.HTTP_400_BAD_REQUEST <= status_code < status.HTTP_500_INTERNAL_SERVER_ERROR: + return _VALIDATION_FAILED + return _INTERNAL + + +class UnhandledErrorMiddleware: + """Answer an unhandled exception with the internal problem. + + Starlette's ServerErrorMiddleware re-raises after its handler, and uvicorn + then logs the exception with its text. Catching the exception here, inside + that middleware, ends it at this boundary: only its type is logged, and the + exception text reaches neither the client nor any log record. When the + response has already started it cannot be replaced, so the exception is + logged and the incomplete response is left for the server to close. + """ + + def __init__(self, app: ASGIApp) -> None: + self._app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self._app(scope, receive, send) + return + + response_started = False + + async def tracked_send(message: Message) -> None: + nonlocal response_started + if message["type"] == "http.response.start": + response_started = True + await send(message) + + try: + await self._app(scope, receive, tracked_send) + except Exception as exc: + request = Request(scope) + # Exception text may contain document content or model output, so + # only the type is logged. + logger.error( + "Unhandled %s in %s %s", + type(exc).__name__, + request.method, + request.url.path, + ) + if response_started: + return + response = _problem_response(request, _INTERNAL) + await response(scope, receive, send) + + +async def _handle_validation_error(request: Request, exc: Exception) -> JSONResponse: + errors = exc.errors() if isinstance(exc, RequestValidationError) else [] + return _problem_response(request, _VALIDATION_FAILED, _field_errors(errors)) + + +async def _handle_http_exception(request: Request, exc: Exception) -> JSONResponse: + status_code = ( + exc.status_code + if isinstance(exc, StarletteHTTPException) + else status.HTTP_500_INTERNAL_SERVER_ERROR + ) + definition = _definition_for_status(status_code) + if definition is _INTERNAL: + logger.error("HTTP status %d in %s %s", status_code, request.method, request.url.path) + raised_headers = exc.headers if isinstance(exc, StarletteHTTPException) else None + headers = { + name: raised_headers[name] + for name in _FORWARDED_HEADERS + if raised_headers and name in raised_headers + } + return _problem_response(request, definition, headers=headers or None) + + +def _problem_response( + request: Request, + definition: _Definition, + errors: list[ProblemFieldError] | None = None, + headers: Mapping[str, str] | None = None, +) -> JSONResponse: + problem = Problem( + type=f"{_TYPE_PREFIX}{definition.code.root}", + title=definition.title, + status=definition.status, + code=definition.code, + detail=definition.detail, + trace_id=_request_id(request), + errors=errors, + ) + return JSONResponse( + content=problem.model_dump(mode="json", by_alias=True, exclude_none=True), + status_code=definition.status, + headers=headers, + media_type=PROBLEM_MEDIA_TYPE, + ) + + +def _request_id(request: Request) -> str | None: + value = request.headers.get(_REQUEST_ID_HEADER) + if value is not None and _REQUEST_ID_PATTERN.fullmatch(value): + return value + return None + + +def _field_errors(errors: Sequence[Any]) -> list[ProblemFieldError]: + fields: list[ProblemFieldError] = [] + for error in errors[:_MAX_FIELD_ERRORS]: + if not isinstance(error, Mapping): + continue + location = tuple(error.get("loc", ())) + names_part = bool(location) and location[0] in _FIELD_LOCATIONS + part = str(location[0]) if names_part else "body" + path = location[1:] if names_part else location + if error.get("type") == "json_invalid": + # The location of a JSON syntax error is a character offset, not a + # field, so the error points at the whole body. + path = () + code = _FIELD_CODE_REQUIRED if error.get("type") == "missing" else _FIELD_CODE_INVALID + fields.append( + ProblemFieldError.model_validate( + { + "in": ProblemFieldLocation.model_validate(part), + "pointer": "".join(f"/{_escape_pointer_token(str(token))}" for token in path), + "code": code, + "message": _FIELD_MESSAGES[code], + } + ) + ) + return fields + + +def _escape_pointer_token(token: str) -> str: + """Escape a JSON Pointer reference token as RFC 6901 requires.""" + return token.replace("~", "~0").replace("/", "~1") diff --git a/ml/src/lincodex_ml/infra/logging.py b/ml/src/lincodex_ml/infra/logging.py index 4e16ada..1f81a0c 100644 --- a/ml/src/lincodex_ml/infra/logging.py +++ b/ml/src/lincodex_ml/infra/logging.py @@ -1,22 +1,32 @@ import json import logging from datetime import UTC, datetime -from typing import override +from typing import Final, override + +# uvicorn configures these loggers with its own text handlers before it imports +# the application. They are routed through the service handler instead, so +# that no uvicorn record prints exception text or a traceback. +UVICORN_LOGGERS: Final = ("uvicorn", "uvicorn.error", "uvicorn.access") class JsonFormatter(logging.Formatter): + """Format records as JSON lines without exception text or tracebacks. + + Exception messages may contain resume text, contact data, or model output, + so a record with exception information keeps only the exception type. + """ + @override def format(self, record: logging.LogRecord) -> str: - return json.dumps( - { - "timestamp": datetime.now(UTC).isoformat(), - "level": record.levelname.lower(), - "logger": record.name, - "message": record.getMessage(), - }, - ensure_ascii=False, - separators=(",", ":"), - ) + entry: dict[str, str] = { + "timestamp": datetime.now(UTC).isoformat(), + "level": record.levelname.lower(), + "logger": record.name, + "message": record.getMessage(), + } + if record.exc_info and record.exc_info[0] is not None: + entry["exception_type"] = record.exc_info[0].__name__ + return json.dumps(entry, ensure_ascii=False, separators=(",", ":")) def configure_logging() -> None: @@ -26,3 +36,7 @@ def configure_logging() -> None: root_logger.handlers.clear() root_logger.addHandler(handler) root_logger.setLevel(logging.INFO) + for name in UVICORN_LOGGERS: + uvicorn_logger = logging.getLogger(name) + uvicorn_logger.handlers.clear() + uvicorn_logger.propagate = True diff --git a/ml/src/lincodex_ml/main.py b/ml/src/lincodex_ml/main.py index fbd2e24..e8035dc 100644 --- a/ml/src/lincodex_ml/main.py +++ b/ml/src/lincodex_ml/main.py @@ -2,6 +2,7 @@ from fastapi import FastAPI from prometheus_client import REGISTRY, make_asgi_app from lincodex_ml.api.health import router as health_router +from lincodex_ml.api.problems import install_problem_handlers from lincodex_ml.infra.logging import configure_logging @@ -9,6 +10,7 @@ def create_app() -> FastAPI: configure_logging() application = FastAPI(title="Lincodex ML Operational API", version="0.1.0") application.openapi_version = "3.1.2" + install_problem_handlers(application) application.include_router(health_router) application.mount("/metrics", make_asgi_app(registry=REGISTRY)) return application diff --git a/ml/tests/test_contract.py b/ml/tests/test_contract.py index 176b4de..126bea5 100644 --- a/ml/tests/test_contract.py +++ b/ml/tests/test_contract.py @@ -6,7 +6,7 @@ import pytest import yaml from pydantic import BaseModel, ValidationError -from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse +from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse, Problem from lincodex_ml.main import app CONTRACT_PATH = Path(__file__).resolve().parents[2] / "api" / "ml" / "openapi.bundle.yml" @@ -20,6 +20,14 @@ def _resolve_schema(document: dict[str, Any], schema: dict[str, Any]) -> dict[st return document["components"]["schemas"][component_name] +def _resolve_response(document: dict[str, Any], response: dict[str, Any]) -> dict[str, Any]: + reference = response.get("$ref") + if reference is None: + return response + component_name = reference.rsplit("/", maxsplit=1)[-1] + return document["components"]["responses"][component_name] + + def _status_values(document: dict[str, Any], response: dict[str, Any]) -> list[str]: content = response["content"]["application/json"]["schema"] response_schema = _resolve_schema(document, content) @@ -47,6 +55,10 @@ def test_health_and_readiness_match_shared_openapi_contract() -> None: assert actual_operation["operationId"] == expected_operation["operationId"] for response_code, expected_response in expected_operation["responses"].items(): + # The default problem response is checked at runtime below; FastAPI + # cannot describe it with the problem media type. + if response_code == "default": + continue actual_response = actual_operation["responses"][response_code] assert _status_values(contract, expected_response) == _status_values( implementation, actual_response @@ -68,6 +80,27 @@ async def test_unready_probe_returns_the_contractual_503_response() -> None: assert response.json()["status"] in _status_values(contract, readiness["503"]) +@pytest.mark.anyio +@pytest.mark.parametrize(("method", "path"), [("POST", "/healthz"), ("GET", "/missing")]) +async def test_error_responses_match_the_contractual_default_response( + method: str, path: str +) -> None: + contract = yaml.safe_load(CONTRACT_PATH.read_text(encoding="utf-8")) + default = _resolve_response( + contract, contract["paths"]["/healthz"]["get"]["responses"]["default"] + ) + (media_type,) = default["content"] + + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as client: + response = await client.request(method, path) + + assert response.headers["content-type"] == media_type + problem = Problem.model_validate(response.json()) + assert problem.status == response.status_code + + @pytest.mark.parametrize( ("model", "valid_status"), [(MLHealthResponse, "ok"), (MLReadinessResponse, "ready"), (MLReadinessResponse, "not_ready")], diff --git a/ml/tests/test_problems.py b/ml/tests/test_problems.py new file mode 100644 index 0000000..6061a3f --- /dev/null +++ b/ml/tests/test_problems.py @@ -0,0 +1,215 @@ +import logging +import logging.config +from typing import Annotated + +import httpx +import pytest +from fastapi import FastAPI, HTTPException, Query +from pydantic import BaseModel +from uvicorn.config import LOGGING_CONFIG + +from lincodex_ml.api.models import Problem +from lincodex_ml.api.problems import PROBLEM_MEDIA_TYPE +from lincodex_ml.infra.logging import UVICORN_LOGGERS, JsonFormatter, configure_logging +from lincodex_ml.main import create_app + +SENSITIVE_TEXT = "resume of Jane Doe, phone +7 900 000-00-00" + + +class ProbeInput(BaseModel): + name: str + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +@pytest.fixture +def probe_app() -> FastAPI: + """The service app plus test-only routes that the ML contract does not have.""" + application = create_app() + + @application.get("/probe") + async def probe(limit: Annotated[int, Query(ge=1, le=100)]) -> dict[str, int]: + return {"limit": limit} + + @application.post("/probe") + async def create_probe(payload: ProbeInput) -> dict[str, str]: + return {"name": payload.name} + + @application.get("/failure") + async def failure() -> None: + raise RuntimeError(SENSITIVE_TEXT) + + @application.get("/status/{code}") + async def raise_status(code: int) -> None: + headers = {"Retry-After": "30"} if code == 429 else None + raise HTTPException(status_code=code, detail=SENSITIVE_TEXT, headers=headers) + + return application + + +async def _request( + application: FastAPI, + method: str, + path: str, + json: object = None, + content: str | None = None, + headers: dict[str, str] | None = None, +) -> httpx.Response: + # Unhandled errors must reach the problem handler instead of the test client. + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=application, raise_app_exceptions=False), + base_url="http://test", + ) as client: + return await client.request(method, path, json=json, content=content, headers=headers) + + +def _problem(response: httpx.Response, status: int, code: str) -> Problem: + assert response.status_code == status + assert response.headers["content-type"] == PROBLEM_MEDIA_TYPE + problem = Problem.model_validate(response.json()) + assert problem.status == status + assert problem.code.root == code + assert problem.type == f"urn:lincodex:problem:{code}" + return problem + + +@pytest.mark.anyio +async def test_unhandled_exception_ends_at_the_problem_boundary(probe_app: FastAPI) -> None: + # The default transport re-raises anything that escapes the application, + # so a problem response here proves that nothing reaches Starlette's + # ServerErrorMiddleware, which would re-raise to uvicorn. + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=probe_app), base_url="http://test" + ) as client: + response = await client.get("/failure", headers={"X-Request-ID": "req-1"}) + + problem = _problem(response, 500, "internal") + assert problem.trace_id == "req-1" + assert "Jane" not in response.text + + +@pytest.mark.anyio +async def test_unhandled_exception_text_reaches_no_log_record( + probe_app: FastAPI, caplog: pytest.LogCaptureFixture +) -> None: + # create_app replaced the root handlers, so capture at the root again. + logging.getLogger().addHandler(caplog.handler) + caplog.set_level(logging.DEBUG) + try: + response = await _request(probe_app, "GET", "/failure") + finally: + logging.getLogger().removeHandler(caplog.handler) + + _problem(response, 500, "internal") + assert any("RuntimeError" in record.getMessage() for record in caplog.records) + formatter = JsonFormatter() + for record in caplog.records: + assert "Jane" not in record.getMessage() + assert "Jane" not in formatter.format(record) + assert record.exc_info is None or "Jane" not in str(record.exc_info[1]) + + +def test_uvicorn_loggers_are_redacted_after_uvicorn_configures_them( + capsys: pytest.CaptureFixture[str], +) -> None: + # uvicorn applies its logging configuration before it imports the + # application; configure_logging then takes its loggers over. + logging.config.dictConfig(LOGGING_CONFIG) + configure_logging() + capsys.readouterr() + + try: + raise RuntimeError(SENSITIVE_TEXT) + except RuntimeError: + logging.getLogger("uvicorn.error").exception("Exception in ASGI application") + + output = capsys.readouterr().err + assert '"exception_type":"RuntimeError"' in output + assert "Exception in ASGI application" in output + assert "Jane" not in output + assert "Traceback" not in output + for name in UVICORN_LOGGERS: + assert logging.getLogger(name).handlers == [] + + +@pytest.mark.anyio +@pytest.mark.parametrize( + ("raised", "status", "code"), + [ + (400, 400, "validation_failed"), + (401, 401, "unauthenticated"), + (403, 403, "forbidden"), + (409, 409, "state_conflict"), + (413, 413, "payload_too_large"), + (415, 415, "unsupported_media_type"), + (422, 400, "validation_failed"), + (428, 428, "precondition_required"), + (429, 429, "rate_limited"), + (501, 501, "not_implemented"), + (418, 400, "validation_failed"), + (503, 500, "internal"), + ], +) +async def test_http_exceptions_map_to_contract_problems( + probe_app: FastAPI, raised: int, status: int, code: str +) -> None: + response = await _request(probe_app, "GET", f"/status/{raised}") + + _problem(response, status, code) + assert "Jane" not in response.text + if raised == 429: + assert response.headers["retry-after"] == "30" + + +@pytest.mark.anyio +@pytest.mark.parametrize( + ("method", "path", "body", "expected"), + [ + ("GET", "/probe?limit=0", None, [{"in": "query", "pointer": "/limit", "code": "invalid"}]), + ("GET", "/probe", None, [{"in": "query", "pointer": "/limit", "code": "required"}]), + ("POST", "/probe", {}, [{"in": "body", "pointer": "/name", "code": "required"}]), + ("POST", "/probe", {"name": 1}, [{"in": "body", "pointer": "/name", "code": "invalid"}]), + ("POST", "/probe", '{"name":', [{"in": "body", "pointer": "", "code": "invalid"}]), + ], +) +async def test_request_validation_returns_validation_problem( + probe_app: FastAPI, + method: str, + path: str, + body: object, + expected: list[dict[str, str]], +) -> None: + if isinstance(body, str): + response = await _request( + probe_app, method, path, content=body, headers={"Content-Type": "application/json"} + ) + else: + response = await _request(probe_app, method, path, json=body) + + problem = _problem(response, 400, "validation_failed") + fields = [ + {"in": field.in_.root, "pointer": field.pointer, "code": field.code} + for field in problem.errors or [] + ] + assert fields == expected + assert all(field.message for field in problem.errors or []) + + +@pytest.mark.anyio +async def test_unknown_route_and_method_return_problems(probe_app: FastAPI) -> None: + missing = await _request(probe_app, "GET", "/missing") + _problem(missing, 404, "not_found") + + not_allowed = await _request(probe_app, "DELETE", "/healthz") + _problem(not_allowed, 405, "method_not_allowed") + assert not_allowed.headers["allow"] == "GET" + + +@pytest.mark.anyio +async def test_invalid_request_id_is_not_echoed(probe_app: FastAPI) -> None: + response = await _request(probe_app, "GET", "/missing", headers={"X-Request-ID": "bad id"}) + + assert _problem(response, 404, "not_found").trace_id is None diff --git a/scripts/README.en.md b/scripts/README.en.md index c90846b..23968f3 100644 --- a/scripts/README.en.md +++ b/scripts/README.en.md @@ -8,7 +8,7 @@ Helper tools that work across multiple parts of the repository. - `check-api-compat.sh` checks public API compatibility against a selected Git ref. - `check-generated.py` detects generated files that differ from Git. - `docs-check.py` checks documentation, README language pairs, and local links. -- `test_docs_check.py` and `test_merge_schemas.py` test documentation validation and schema merging. +- `test_docs_check.py` and `test_merge_schemas.py` test documentation validation and schema merging; `test_contract_copies.py` checks that the OpenAPI 3.2 fixture and the ML contract keep identical copies of the api/core conventions. Run them through Make from the repository root: `make -C api check`, `make -C api check-compat API_BASE_REF=`, `make check-generated`, and `make docs-check`. Service-specific scripts live in their service directories. diff --git a/scripts/README.md b/scripts/README.md index e217b8b..fab9e63 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -8,7 +8,7 @@ - `check-api-compat.sh` проверяет совместимость публичного API с выбранной Git-ссылкой. - `check-generated.py` обнаруживает расхождения сгенерированных файлов с Git. - `docs-check.py` проверяет документацию, языковые пары README и локальные ссылки. -- `test_docs_check.py` и `test_merge_schemas.py` проверяют валидацию документации и объединение схем. +- `test_docs_check.py` и `test_merge_schemas.py` проверяют валидацию документации и объединение схем; `test_contract_copies.py` проверяет, что фикстура OpenAPI 3.2 и ML-контракт хранят идентичные копии соглашений api/core. Запускайте их через Make из корня: `make -C api check`, `make -C api check-compat API_BASE_REF=`, `make check-generated` и `make docs-check`. Скрипты конкретного сервиса находятся в его каталоге. diff --git a/scripts/test_contract_copies.py b/scripts/test_contract_copies.py new file mode 100644 index 0000000..5e6a115 --- /dev/null +++ b/scripts/test_contract_copies.py @@ -0,0 +1,107 @@ +"""Check that contract convention copies stay identical to api/core. + +The OpenAPI 3.2 compatibility fixture and the ML contract cannot reference +api/core files: ogen rejects external references and the ML contract is a +separate specification. They therefore carry copies of the api/core +conventions. These tests read the bundled api/core contract, so run them after +`make -C api bundle`. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path +from typing import Any + +import yaml + +API_DIR = Path(__file__).resolve().parents[1] / "api" +CORE_BUNDLE = API_DIR / "core" / "openapi.bundle.yml" +ML_BUNDLE = API_DIR / "ml" / "openapi.bundle.yml" +FIXTURE = API_DIR / "testdata" / "openapi-3.2.0.yml" +SHARED_SECTIONS = ("schemas", "parameters", "headers") +# Every api/core convention component that the fixture must exercise. +EXPECTED_FIXTURE_COPIES = { + ("schemas", "Problem"), + ("schemas", "ProblemCode"), + ("schemas", "ProblemFieldError"), + ("schemas", "ProblemFieldLocation"), + ("schemas", "Timestamp"), + ("schemas", "PageInfo"), + ("parameters", "IdempotencyKey"), + ("parameters", "IfMatch"), + ("parameters", "PageLimit"), + ("parameters", "PageCursor"), + ("headers", "ETag"), +} +PROBLEM_SCHEMAS = ("Problem", "ProblemCode", "ProblemFieldError", "ProblemFieldLocation") + + +def load_components(path: Path) -> dict[str, Any]: + with path.open(encoding="utf-8") as stream: + document = yaml.safe_load(stream) + components = document.get("components") + if not isinstance(components, dict): + raise AssertionError(f"{path} has no components mapping") + return components + + +def without_descriptions(value: Any) -> Any: + """Return a copy of a schema without description text.""" + if isinstance(value, dict): + return { + key: without_descriptions(item) + for key, item in value.items() + if key != "description" + } + if isinstance(value, list): + return [without_descriptions(item) for item in value] + return value + + +def without_examples(response: dict[str, Any]) -> dict[str, Any]: + """Return a copy of a response without media type examples.""" + content = { + media_type: {key: item for key, item in media.items() if key != "examples"} + for media_type, media in response.get("content", {}).items() + } + return {**response, "content": content} + + +class ContractCopiesTest(unittest.TestCase): + def setUp(self) -> None: + self.core = load_components(CORE_BUNDLE) + + def test_fixture_copies_match_core_definitions(self) -> None: + fixture = load_components(FIXTURE) + compared = set() + for section in SHARED_SECTIONS: + for name, definition in fixture.get(section, {}).items(): + if name not in self.core.get(section, {}): + continue + compared.add((section, name)) + with self.subTest(section=section, name=name): + self.assertEqual(definition, self.core[section][name]) + self.assertEqual(compared, EXPECTED_FIXTURE_COPIES) + + def test_fixture_responses_match_core_without_examples(self) -> None: + fixture_responses = load_components(FIXTURE)["responses"] + for name, definition in fixture_responses.items(): + with self.subTest(name=name): + self.assertIn(name, self.core["responses"]) + expected = without_examples(self.core["responses"][name]) + self.assertEqual(definition, expected) + + def test_ml_problem_schemas_match_core_except_descriptions(self) -> None: + ml_schemas = load_components(ML_BUNDLE)["schemas"] + for name in PROBLEM_SCHEMAS: + with self.subTest(name=name): + self.assertIn(name, ml_schemas) + self.assertEqual( + without_descriptions(ml_schemas[name]), + without_descriptions(self.core["schemas"][name]), + ) + + +if __name__ == "__main__": + unittest.main() From 197661145e9e5de5f18e5a0e26e2656fa07582fd Mon Sep 17 00:00:00 2001 From: shira Date: Mon, 5 Oct 2026 22:28:30 +0300 Subject: [PATCH 004/143] feat(deploy): add internal Kafka KRaft broker and Go broker settings --- .agents/standards/infrastructure.md | 4 +- .env.example | 6 +++ backend/config/config.go | 5 ++ backend/config/config_test.go | 60 +++++++++++++++++++++ backend/config/kafka.go | 83 +++++++++++++++++++++++++++++ deploy/Makefile | 2 +- deploy/README.en.md | 2 +- deploy/README.md | 2 +- deploy/docker/docker-compose.yml | 70 ++++++++++++++++++++++++ deploy/scripts/smoke.sh | 2 +- docs/en/ARCHITECTURE.md | 4 +- docs/en/DEPLOY.md | 26 ++++++++- docs/en/DEVELOPMENT.md | 5 +- docs/ru/ARCHITECTURE.md | 4 +- docs/ru/DEPLOY.md | 26 ++++++++- docs/ru/DEVELOPMENT.md | 5 +- 16 files changed, 289 insertions(+), 17 deletions(-) create mode 100644 backend/config/kafka.go diff --git a/.agents/standards/infrastructure.md b/.agents/standards/infrastructure.md index 6095c14..a0e692c 100644 --- a/.agents/standards/infrastructure.md +++ b/.agents/standards/infrastructure.md @@ -8,10 +8,12 @@ The core frontend container serves static assets with Nginx and proxies /api to The ML Compose file binds to 127.0.0.1:8000 by default. A remote ML host needs an explicit private bind address, restricted firewall rules, and a deliberate scrape target. Leave ML_METRICS_TARGET empty when Prometheus must not scrape a remote ML host. -Start the core project before monitoring because monitoring joins its Docker network. The monitoring Compose project collects only the explicitly configured core services. Do not expose PostgreSQL, Redis, SeaweedFS, backend metrics, Prometheus, Loki, exporters, or the Docker socket proxy publicly. +Start the core project before monitoring because monitoring joins its Docker network. The monitoring Compose project collects only the explicitly configured core services. Do not expose PostgreSQL, Redis, SeaweedFS, Kafka, backend metrics, Prometheus, Loki, exporters, or the Docker socket proxy publicly. Redis runs in the core project with password authentication, bounded memory, allkeys-lru eviction, and persistence disabled. Keep it private to the Compose network. The separate monitoring project supplies redis-exporter; ML does not use Redis in the current scaffold. +Kafka runs in the core project as one internal KRaft broker and controller with a bounded JVM heap, a memory limit, and a named volume. Keep its listener private to the Compose network and create topics explicitly; it carries events only through the transactional outbox. + SeaweedFS runs as a single-node S3-compatible server in the core project. Persist both data and metadata in its named volume. Keep every storage port private; require credentials for S3 access. Nginx does not proxy private objects directly. Ordinary shutdown preserves the volume; this local setup does not provide HA or off-host backups. Use the repository's Compose and observability Make targets to render and validate configuration. Keep secrets in a local .env or deployment secret store, not in committed examples. Do not claim TLS, public availability, multi-node reliability, or a successful deploy based on Compose syntax checks. diff --git a/.env.example b/.env.example index 5bca2ed..c0cdf6d 100644 --- a/.env.example +++ b/.env.example @@ -13,6 +13,12 @@ SEAWEEDFS_ACCESS_KEY=lincodex-local SEAWEEDFS_SECRET_KEY=replace-this-storage-secret SEAWEEDFS_BUCKET=lincodex +# Kafka KRaft cluster identifier. It is not a secret and grants no access; it +# ties the formatted log directory to one cluster. Generate your own value with +# `docker run --rm apache/kafka:latest /opt/kafka/bin/kafka-storage.sh random-uuid` +# before the first start; changing it later stops Kafka from using the existing volume. +KAFKA_CLUSTER_ID=SJv4PXUUSJGbK3eSPC57qA + # Optional PostgreSQL metrics login, created when the database volume is initialized. POSTGRES_EXPORTER_USER=metrics_reader POSTGRES_EXPORTER_PASSWORD=replace-this-metrics-password diff --git a/backend/config/config.go b/backend/config/config.go index 949db5e..b6fa307 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -35,6 +35,7 @@ type Config struct { SeaweedFSBucket string SeaweedFSRegion string SeaweedFSTimeout time.Duration + KafkaBrokers []string LogLevel string ReadinessTimeout time.Duration ShutdownTimeout time.Duration @@ -60,6 +61,7 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { SeaweedFSBucket: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_BUCKET", defaultSeaweedFSBucket)), SeaweedFSRegion: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_REGION", defaultSeaweedFSRegion)), SeaweedFSTimeout: defaultSeaweedFSTimeout, + KafkaBrokers: parseKafkaBrokers(valueOrDefault(lookup, "KAFKA_BROKERS", defaultKafkaBrokers)), LogLevel: strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "LOG_LEVEL", defaultLogLevel))), ReadinessTimeout: defaultReadinessTimeout, ShutdownTimeout: defaultShutdownTimeout, @@ -98,6 +100,9 @@ func (config Config) Validate() error { if err := config.ValidateRedis(); err != nil { return err } + if err := config.ValidateKafka(); err != nil { + return err + } if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil { return err } diff --git a/backend/config/config_test.go b/backend/config/config_test.go index 4a0a349..077c28c 100644 --- a/backend/config/config_test.go +++ b/backend/config/config_test.go @@ -1,6 +1,7 @@ package config import ( + "slices" "strings" "testing" "time" @@ -26,6 +27,9 @@ func TestLoadFromEnvUsesOperationalDefaults(t *testing.T) { if config.LogLevel != "info" { t.Fatalf("LogLevel = %q, want info", config.LogLevel) } + if !slices.Equal(config.KafkaBrokers, []string{"localhost:9092"}) { + t.Fatalf("KafkaBrokers = %q, want the localhost default", config.KafkaBrokers) + } } func TestLoadFromEnvReadsAddressesAndTimeouts(t *testing.T) { @@ -169,3 +173,59 @@ func TestLoadFromEnvRejectsSeaweedFSSettings(t *testing.T) { }) } } + +func TestLoadFromEnvKafkaBrokers(t *testing.T) { + tests := []struct { + name string + value string + want []string + }{ + {name: "single Compose broker", value: "kafka:9092", want: []string{"kafka:9092"}}, + {name: "trimmed list", value: " kafka-1:9092 , 10.0.0.2:9093,[::1]:9094 ", want: []string{"kafka-1:9092", "10.0.0.2:9093", "[::1]:9094"}}, + {name: "fully qualified name", value: "broker_1.internal.example:9092", want: []string{"broker_1.internal.example:9092"}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{"KAFKA_BROKERS": test.value})) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if !slices.Equal(settings.KafkaBrokers, test.want) { + t.Fatalf("KafkaBrokers = %q, want %q", settings.KafkaBrokers, test.want) + } + }) + } +} + +func TestLoadFromEnvRejectsKafkaBrokers(t *testing.T) { + tests := []struct { + name string + value string + want string + }{ + {name: "explicitly empty", value: "", want: "Config.ValidateKafka - KAFKA_BROKERS must not be empty"}, + {name: "only spaces", value: " ", want: "Config.ValidateKafka - KAFKA_BROKERS must not be empty"}, + {name: "missing port", value: "kafka", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "empty host", value: ":9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "zero port", value: "kafka:0", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "port out of range", value: "kafka:70000", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "named port", value: "kafka:broker", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "empty middle entry", value: "kafka-1:9092,,kafka-2:9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 2"}, + {name: "trailing separator", value: "kafka:9092,", want: "Config.ValidateKafka - KAFKA_BROKERS entry 2"}, + {name: "URL scheme", value: "PLAINTEXT://kafka:9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "user info", value: "user:secret@kafka:9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "path", value: "kafka/events:9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "label with leading hyphen", value: "-kafka:9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(map[string]string{"KAFKA_BROKERS": test.value})) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want) + } + if strings.Contains(err.Error(), "secret") { + t.Fatal("configuration error disclosed the broker value") + } + }) + } +} diff --git a/backend/config/kafka.go b/backend/config/kafka.go new file mode 100644 index 0000000..aa1b4bb --- /dev/null +++ b/backend/config/kafka.go @@ -0,0 +1,83 @@ +package config + +import ( + "errors" + "fmt" + "net" + "strconv" + "strings" +) + +const ( + defaultKafkaBrokers = "localhost:9092" + kafkaBrokersSeparator = "," +) + +// parseKafkaBrokers splits a comma-separated broker list. Empty entries are +// kept so that validation can reject values such as "a:9092,,b:9092". +func parseKafkaBrokers(raw string) []string { + if strings.TrimSpace(raw) == "" { + return nil + } + entries := strings.Split(raw, kafkaBrokersSeparator) + brokers := make([]string, 0, len(entries)) + for _, entry := range entries { + brokers = append(brokers, strings.TrimSpace(entry)) + } + return brokers +} + +func (config Config) ValidateKafka() error { + if len(config.KafkaBrokers) == 0 { + return errors.New("Config.ValidateKafka - KAFKA_BROKERS must not be empty") + } + for index, broker := range config.KafkaBrokers { + // Report the position instead of the value so a mistyped entry with + // embedded credentials does not reach logs. + if !validKafkaBroker(broker) { + return fmt.Errorf("Config.ValidateKafka - KAFKA_BROKERS entry %d must be a host:port address with a nonzero port", index+1) + } + } + return nil +} + +// validKafkaBroker accepts a hostname or IP address with a port in 1-65535. +// URL schemes, user info, and paths are rejected because Kafka clients expect +// plain bootstrap addresses. +func validKafkaBroker(broker string) bool { + host, port, err := net.SplitHostPort(broker) + if err != nil { + return false + } + number, err := strconv.Atoi(port) + if err != nil || number < 1 || number > maxPortNumber { + return false + } + return net.ParseIP(host) != nil || validHostname(host) +} + +func validHostname(host string) bool { + if host == "" { + return false + } + for _, label := range strings.Split(host, ".") { + if !validHostnameLabel(label) { + return false + } + } + return true +} + +func validHostnameLabel(label string) bool { + if label == "" || strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") { + return false + } + for _, character := range label { + isLetter := (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') + isDigit := character >= '0' && character <= '9' + if !isLetter && !isDigit && character != '-' && character != '_' { + return false + } + } + return true +} diff --git a/deploy/Makefile b/deploy/Makefile index 0d44ed1..50d7885 100644 --- a/deploy/Makefile +++ b/deploy/Makefile @@ -28,7 +28,7 @@ config: ## Render all Compose files with safe example values build: ## Build local frontend and backend images APP_PROJECT="$(APP_PROJECT)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" build -up: ## Start the core app, PostgreSQL, Redis, and SeaweedFS without monitoring +up: ## Start the core app, PostgreSQL, Redis, SeaweedFS, and Kafka without monitoring @test -f "$(ENV_FILE)" || { printf 'Missing %s. Copy .env.example to .env and replace the placeholder passwords.\n' "$(ENV_FILE)" >&2; exit 2; } APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" up -d diff --git a/deploy/README.en.md b/deploy/README.en.md index 25dd290..4ed72bb 100644 --- a/deploy/README.en.md +++ b/deploy/README.en.md @@ -4,7 +4,7 @@ Configuration for running the application with Docker Compose and Nginx. -- `docker/docker-compose.yml` starts the core stack with PostgreSQL, Redis, and SeaweedFS. +- `docker/docker-compose.yml` starts the core stack with PostgreSQL, Redis, SeaweedFS, and Kafka. - `docker/docker-compose.ml.yml` and `docker/docker-compose.monitoring.yml` run ML and monitoring as separate projects. - `nginx/` configures frontend serving and API proxying. - `scripts/` contains the isolated stack smoke check. diff --git a/deploy/README.md b/deploy/README.md index 0f6316e..249cb66 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -4,7 +4,7 @@ Конфигурация запуска через Docker Compose и Nginx. -- `docker/docker-compose.yml` поднимает основной стек с PostgreSQL, Redis и SeaweedFS. +- `docker/docker-compose.yml` поднимает основной стек с PostgreSQL, Redis, SeaweedFS и Kafka. - `docker/docker-compose.ml.yml` и `docker/docker-compose.monitoring.yml` запускают ML и мониторинг отдельными проектами. - `nginx/` содержит конфигурацию раздачи frontend и проксирования API. - `scripts/` содержит smoke-проверку изолированного стека. diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 4e1315c..96558e3 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -103,6 +103,73 @@ services: cpus: "1.0" memory: 1G + kafka: + image: apache/kafka:latest + environment: + # Setting any KAFKA_* property disables the image's default + # server.properties, so every required broker setting is listed here. + CLUSTER_ID: ${KAFKA_CLUSTER_ID:?Set KAFKA_CLUSTER_ID in the root .env file} + KAFKA_NODE_ID: "1" + KAFKA_PROCESS_ROLES: broker,controller + # The controller listener stays on container loopback; only the + # client listener is reachable on the Compose network. + KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092,CONTROLLER://127.0.0.1:9093 + KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092 + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT + KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER + KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT + KAFKA_CONTROLLER_QUORUM_VOTERS: 1@127.0.0.1:9093 + KAFKA_LOG_DIRS: /var/lib/kafka/data + KAFKA_AUTO_CREATE_TOPICS_ENABLE: "false" + KAFKA_NUM_PARTITIONS: "1" + KAFKA_DEFAULT_REPLICATION_FACTOR: "1" + KAFKA_MIN_INSYNC_REPLICAS: "1" + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: "1" + KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: "1" + KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: "1" + KAFKA_SHARE_COORDINATOR_STATE_TOPIC_REPLICATION_FACTOR: "1" + KAFKA_SHARE_COORDINATOR_STATE_TOPIC_MIN_ISR: "1" + KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: "0" + KAFKA_LOG_RETENTION_HOURS: "168" + KAFKA_LOG_RETENTION_BYTES: "1073741824" + KAFKA_LOG_SEGMENT_BYTES: "134217728" + KAFKA_HEAP_OPTS: -Xms256m -Xmx512m + # An empty value lets the image enable an unauthenticated JMX agent with + # an RMI port on all container interfaces. This non-empty value opens no + # JMX port; metrics export is not configured yet. + KAFKA_JMX_OPTS: -Djava.rmi.server.hostname=127.0.0.1 + volumes: + - kafka_data:/var/lib/kafka/data + # The image declares these paths as volumes for TLS material and config + # overrides. Neither is used here; tmpfs avoids an anonymous volume per + # container recreation. + tmpfs: + - /etc/kafka/secrets:size=1m,mode=0755 + - /mnt/shared/config:size=1m,mode=0755 + expose: + - "9092" + healthcheck: + # CLI tools inherit KAFKA_HEAP_OPTS, so the probe gets its own small heap + # to stay inside the container memory limit next to the broker. + test: ["CMD-SHELL", "KAFKA_HEAP_OPTS='-Xms32m -Xmx64m' /opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server localhost:9092 >/dev/null 2>&1"] + interval: 15s + timeout: 10s + retries: 10 + start_period: 30s + # Allow a controlled shutdown so the next start skips log recovery. + stop_grace_period: 30s + restart: unless-stopped + logging: + driver: json-file + options: + max-size: 10m + max-file: "3" + deploy: + resources: + limits: + cpus: "1.0" + memory: 1G + backend: build: context: ../../backend @@ -119,6 +186,7 @@ services: SEAWEEDFS_BUCKET: ${SEAWEEDFS_BUCKET:?Set SEAWEEDFS_BUCKET in the root .env file} SEAWEEDFS_REGION: us-east-1 SEAWEEDFS_TIMEOUT: 10s + KAFKA_BROKERS: kafka:9092 depends_on: postgres: condition: service_healthy @@ -173,6 +241,8 @@ volumes: name: ${APP_PROJECT:-app}_postgres_data seaweedfs_data: name: ${APP_PROJECT:-app}_seaweedfs_data + kafka_data: + name: ${APP_PROJECT:-app}_kafka_data networks: default: diff --git a/deploy/scripts/smoke.sh b/deploy/scripts/smoke.sh index 87eff21..093bcf4 100644 --- a/deploy/scripts/smoke.sh +++ b/deploy/scripts/smoke.sh @@ -18,7 +18,7 @@ compose() { "$@" } -for volume in "${project}_postgres_data" "${project}_seaweedfs_data"; do +for volume in "${project}_postgres_data" "${project}_seaweedfs_data" "${project}_kafka_data"; do if docker volume inspect "$volume" >/dev/null 2>&1; then printf 'Refusing to use existing smoke volume %s.\n' "$volume" >&2 exit 2 diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index c049e31..95000d7 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -50,7 +50,7 @@ Redis is part of the core Compose project and connects through `backend/internal SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. Resume uploads, authorization, content limits, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup. -The MVP does not add a separate vector database, a broker, Kubernetes, or a search microservice. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help. +The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, while the Go client, outbox, and relay are not implemented yet. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help. ## Repository map and package purpose @@ -210,7 +210,7 @@ The target screen stack is React Router, TanStack Query, React Hook Form, and Zo ## Future extensions -PostgreSQL jobs are enough for the MVP. A broker needs an outbox, idempotency, ordering, retries, and deduplication. RabbitMQ/NATS fit independent consumers and routing. Kafka needs a durable stream with multiple consumers and a measured volume. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI. +Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node; the outbox, relay, topics, and consumers are planned and not implemented. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI. k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 4fc4a94..3c78fc1 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -9,7 +9,7 @@ Install Docker Engine and the Docker Compose plugin. At the repository root, cop make -C deploy config make -C deploy up -deploy/docker/docker-compose.yml starts PostgreSQL, Redis, SeaweedFS, the Go backend, and the frontend container. Nginx in the frontend container serves static assets and proxies /api to Go. PostgreSQL, Redis, SeaweedFS, Go, and Nginx communicate on the Compose network. +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. The backend build context is `backend/`, so Docker applies `backend/.dockerignore`. Local tools, caches, environment files, and build outputs are excluded from that context. @@ -39,6 +39,27 @@ Backend settings are `SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, `SEAWEEDFS_SE Ordinary `down` preserves the SeaweedFS volume. Losing the volume loses both objects and metadata; prepare a verified backup before changing the image or deleting the volume. This is one node without HA, cross-node replication, or configured off-host backups. +Kafka uses the official `apache/kafka:latest` image as one KRaft node that combines the broker and controller roles; there is no ZooKeeper. Clients use the PLAINTEXT listener at `kafka:9092`, which is reachable only inside the Compose network and publishes no host port. The controller listener binds to `127.0.0.1:9093` inside the container, so other containers cannot reach it. The client listener has no TLS, authentication, or ACLs: any container attached to the Compose network, including monitoring services that join it, can produce and consume. Keep the network private and do not publish the port. + +The named `kafka_data` volume mounts at `/var/lib/kafka/data` and stores topic logs, consumer offsets, and KRaft metadata, so events survive container restarts and an ordinary `down`. `KAFKA_HEAP_OPTS` bounds the JVM heap to `-Xms256m -Xmx512m`, and the container memory limit is 1 GB. The image's default JMX agent is disabled, so no JMX port is open. Topic data is kept for 7 days or up to 1 GiB per partition, whichever limit is reached first, in 128 MiB segments. Replication factors and the minimum in-sync replica count are 1 because there is one node. This node provides no HA or replication; losing the volume loses all events and consumer offsets. + +`KAFKA_CLUSTER_ID` in `.env` is required. It identifies the KRaft cluster that formatted the volume. It is not a credential and grants no access, so `.env.example` contains a sample value. Generate your own value once before the first start: + + docker run --rm apache/kafka:latest /opt/kafka/bin/kafka-storage.sh random-uuid + +Changing the value after the volume is formatted stops Kafka from starting with that volume. + +Automatic topic creation is disabled: writing to a missing topic fails instead of creating it. Create each topic explicitly; provisioning topics for product events belongs to later work. Kafka CLI tools inherit the broker's `KAFKA_HEAP_OPTS`, so give them a small heap when running them in the container. For example, a manual technical check with the default `app` project: + + docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ + exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-topics.sh \ + --bootstrap-server localhost:9092 --create --topic lincodex.technical.probe \ + --partitions 1 --replication-factor 1 + +The Compose health check runs `kafka-broker-api-versions.sh` against `localhost:9092`, so Kafka is healthy only after the broker answers API requests. `make -C deploy smoke` waits for that health check together with the other core services; it does not publish or read events. + +The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` bootstrap addresses. Compose supplies `kafka:9092`; a directly launched Go process defaults to `localhost:9092`. An explicitly empty value, an empty list entry, a missing or zero port, or a URL scheme fails configuration. The backend has no Kafka client yet: it does not wait for Kafka at startup, and `/readyz` does not check Kafka. The advertised address `kafka:9092` resolves only inside the Compose network, so direct execution needs a separately reachable broker. Redis stays a cache and is not used as a queue. + down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop. ## Separate ML Compose project @@ -65,7 +86,7 @@ Start the core project first. Monitoring joins its Docker network. Monitoring st Grafana is available at http://127.0.0.1:3000. Credentials come from GRAFANA_ADMIN_USER and GRAFANA_ADMIN_PASSWORD in .env. Prometheus, Loki, exporters, and backend metrics publish no host ports. -Prometheus retains metrics for 14 days with a 4 GB size limit. Loki retains logs for 7 days. Alloy discovery filters by Compose project and collects logs only from backend, frontend, postgres, redis, and seaweedfs. Loki labels are limited to service and environment; do not add user IDs, addresses, resume text, request bodies, or full URLs. +Prometheus retains metrics for 14 days with a 4 GB size limit. Loki retains logs for 7 days. Alloy discovery filters by Compose project and collects logs only from backend, frontend, postgres, redis, and seaweedfs. Kafka logs and metrics are not collected yet; read the logs with `make -C deploy logs`. Loki labels are limited to service and environment; do not add user IDs, addresses, resume text, request bodies, or full URLs. Frontend telemetry is not connected in the React app yet. Nginx and Alloy provide a restricted /telemetry receiver and Faro configuration, but the UI SDK and end-to-end event check are absent. @@ -83,6 +104,7 @@ Container images use moving `latest` or `alpine` tags where the upstream publish | --- | --- | --- | | PostgreSQL | Docker Official Image, docker-library/postgres | PostgreSQL License for the server; packaging repository is MIT | | SeaweedFS | chrislusf/seaweedfs | [Apache-2.0](https://github.com/seaweedfs/seaweedfs/blob/master/LICENSE) | +| Apache Kafka | apache/kafka, the Apache Kafka project's image | [Apache-2.0](https://github.com/apache/kafka/blob/trunk/LICENSE) | | Prometheus | prom/prometheus | Apache-2.0 | | Loki | grafana/loki | AGPL-3.0-only by default; see LICENSING.md exceptions | | Grafana Alloy | grafana/alloy | Apache-2.0 by default | diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index ad2d8e2..bcd6883 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -50,11 +50,12 @@ 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, and a 404 for an unknown API route; it does not start ML. - Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap. - 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 a home page, a generated API client, and MSW handlers. -- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). +- 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`). +- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the backend has no Go Kafka client, topics, or readiness check for Kafka. - 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, consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, mail delivery, Kafka/outbox, notifications, support, and an end-to-end business suite. backend/db/migrations/ has no business schema, product usecase and adapter directories 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, consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, mail delivery, the Go Kafka client, the transactional outbox and its relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ has no business schema, product usecase and adapter directories 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 diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 3073f58..064921b 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -50,7 +50,7 @@ Redis входит в основной Compose и подключен через SeaweedFS работает отдельным сервером в основном Compose. `backend/internal/adapter/secondary/seaweedfs/` реализует outbound-порт `ObjectStorage` через AWS SDK for Go v2: потоковые Put/Get и удаление объекта. SDK и S3-типы не выходят за границу адаптера. Bootstrap создает клиент, readiness проверяет bucket через HeadBucket. Хранилище закрыто внутри Docker-сети; Nginx не раздает его файлы напрямую. Загрузка резюме, проверка прав, ограничения содержимого и выдача PDF остаются будущими продуктовыми сценариями. Одноузловой Compose сохраняет данные и метаданные в volume, но не обеспечивает HA или внешнее резервное копирование. -Для MVP не вводятся отдельная vector DB, брокер, Kubernetes или микросервисы поиска. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу. +Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, а Go клиент, outbox и relay пока не реализованы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу. ## Структура репозитория и назначение пакетов @@ -210,7 +210,7 @@ contact_grant относится к паре кандидат-компания ## Будущее расширение -PostgreSQL jobs остаются достаточными на MVP. При необходимости брокера сначала проектируются outbox, идемпотентность, порядок, retry и дедупликация. RabbitMQ/NATS требуют независимых consumers/маршрутизации; Kafka - долговечного потока с несколькими потребителями и измеримым объемом. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера. +Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka; outbox, relay, топики и потребители запланированы и не реализованы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера. k3s не входит в критический путь. Его можно рассмотреть при готовом обслуживаемом кластере или измеренной потребности в нескольких узлах. Один узел k3s не дает HA. Переход требует probes/resources, секретов, storage backup, ingress и проверенных NetworkPolicy. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index aed6bbb..0228654 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -11,7 +11,7 @@ В текущем Compose `POSTGRES_PASSWORD` без URL-кодирования подставляется в `DATABASE_URL`. Используйте пароль из URL-safe символов, например случайную hex-строку. Символы `@`, `/`, `:`, `?`, `#` и `%` пока нельзя вводить в значение без доработки кодирования URI. -Основной файл deploy/docker/docker-compose.yml запускает PostgreSQL, Redis, SeaweedFS, Go backend и frontend контейнер. Frontend контейнер раздает статические файлы через Nginx и проксирует /api в backend. PostgreSQL, Redis, SeaweedFS, backend и Nginx общаются по выделенной Compose сети. +Основной файл deploy/docker/docker-compose.yml запускает PostgreSQL, Redis, SeaweedFS, Kafka, Go backend и frontend контейнер. Frontend контейнер раздает статические файлы через Nginx и проксирует /api в backend. PostgreSQL, Redis, SeaweedFS, Kafka, backend и Nginx общаются по выделенной Compose сети. Контекст сборки backend - каталог `backend/`, поэтому Docker применяет `backend/.dockerignore`. Локальные инструменты, кеши, файлы окружения и результаты сборки не отправляются в этот build context. @@ -41,6 +41,27 @@ Backend использует `SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, `SEAW Обычный `down` сохраняет volume SeaweedFS. Потеря volume означает потерю объектов и метаданных; перед изменением образа или удалением volume нужен проверенный backup. Это один узел без HA, репликации между узлами или настроенного внешнего резервного копирования. +Kafka использует официальный образ `apache/kafka:latest` в виде одного узла KRaft, совмещающего роли broker и controller; ZooKeeper не используется. Клиенты подключаются к PLAINTEXT listener `kafka:9092`, который доступен только внутри Compose сети; порт на хосте не публикуется. Controller listener слушает `127.0.0.1:9093` внутри контейнера, поэтому другие контейнеры к нему не подключаются. У клиентского listener нет TLS, аутентификации и ACL: любой контейнер в Compose сети, включая сервисы мониторинга, которые к ней подключаются, может писать и читать события. Держите сеть закрытой и не публикуйте порт. + +Именованный volume `kafka_data` смонтирован в `/var/lib/kafka/data` и хранит логи топиков, offsets потребителей и метаданные KRaft, поэтому события сохраняются при перезапуске контейнера и обычном `down`. `KAFKA_HEAP_OPTS` ограничивает heap JVM значениями `-Xms256m -Xmx512m`, лимит памяти контейнера - 1 GB. JMX agent образа по умолчанию отключен, JMX порт не открывается. Данные топиков хранятся 7 дней или до 1 GiB на партицию, в зависимости от того, какой лимит достигнут раньше, сегментами по 128 MiB. Факторы репликации и минимальное число in-sync реплик равны 1, потому что узел один. Этот узел не дает HA и репликации; потеря volume означает потерю всех событий и offsets потребителей. + +`KAFKA_CLUSTER_ID` в `.env` обязателен. Он идентифицирует KRaft кластер, который отформатировал volume. Это не учетные данные и не дает доступа, поэтому `.env.example` содержит пример значения. Сгенерируйте собственное значение один раз до первого запуска: + + docker run --rm apache/kafka:latest /opt/kafka/bin/kafka-storage.sh random-uuid + +После форматирования volume смена значения не даст Kafka запуститься с этим volume. + +Автоматическое создание топиков отключено: запись в отсутствующий топик завершается ошибкой, а не создает его. Создавайте каждый топик явно; создание топиков для продуктовых событий относится к следующим задачам. CLI-утилиты Kafka наследуют `KAFKA_HEAP_OPTS` брокера, поэтому при запуске в контейнере задавайте им небольшой heap. Пример ручной технической проверки для проекта по умолчанию `app`: + + docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ + exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-topics.sh \ + --bootstrap-server localhost:9092 --create --topic lincodex.technical.probe \ + --partitions 1 --replication-factor 1 + +Compose healthcheck запускает `kafka-broker-api-versions.sh` против `localhost:9092`, поэтому Kafka считается healthy только после того, как брокер отвечает на API-запросы. `make -C deploy smoke` ждет этот healthcheck вместе с остальными core сервисами, но не публикует и не читает события. + +Backend получает `KAFKA_BROKERS` - список адресов bootstrap в формате `host:port` через запятую. Compose задает `kafka:9092`; прямой запуск Go по умолчанию использует `localhost:9092`. Явно пустое значение, пустой элемент списка, отсутствующий или нулевой порт либо схема URL приводят к ошибке конфигурации. Kafka клиента в backend пока нет: backend не ждет Kafka при старте, а `/readyz` ее не проверяет. Объявленный адрес `kafka:9092` разрешается только внутри Compose сети, поэтому для прямого запуска нужен отдельно доступный брокер. Redis остается кешем и не используется как очередь. + down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова. ## Отдельный ML Compose @@ -67,7 +88,7 @@ GET /healthz проверяет процесс. GET /readyz проверяет Grafana доступна на http://127.0.0.1:3000. Учетные данные берутся из GRAFANA_ADMIN_USER и GRAFANA_ADMIN_PASSWORD в .env. Prometheus, Loki, exporters и backend metrics не публикуют host ports. -Prometheus хранит метрики 14 дней с лимитом 4 GB. Loki хранит логи 7 дней. Alloy discovery отфильтровывает Compose project и принимает логи только backend, frontend, postgres, redis и seaweedfs. Разрешенные Loki labels ограничены service и environment; не добавляйте user ID, адреса, resume content, request body или полный URL в labels. +Prometheus хранит метрики 14 дней с лимитом 4 GB. Loki хранит логи 7 дней. Alloy discovery отфильтровывает Compose project и принимает логи только backend, frontend, postgres, redis и seaweedfs. Логи и метрики Kafka пока не собираются; читайте логи через `make -C deploy logs`. Разрешенные Loki labels ограничены service и environment; не добавляйте user ID, адреса, resume content, request body или полный URL в labels. Frontend телеметрия пока не подключена в React-приложении. Nginx и Alloy имеют ограниченный /telemetry приемник и конфигурацию Faro, однако UI SDK и сквозная проверка событий отсутствуют. @@ -85,6 +106,7 @@ Frontend телеметрия пока не подключена в React-при | --- | --- | --- | | PostgreSQL | Docker Official Image, docker-library/postgres | PostgreSQL License для сервера; packaging repo MIT | | SeaweedFS | chrislusf/seaweedfs | [Apache-2.0](https://github.com/seaweedfs/seaweedfs/blob/master/LICENSE) | +| Apache Kafka | apache/kafka, образ проекта Apache Kafka | [Apache-2.0](https://github.com/apache/kafka/blob/trunk/LICENSE) | | Prometheus | prom/prometheus | Apache-2.0 | | Loki | grafana/loki | AGPL-3.0-only по умолчанию; см. LICENSING.md исключения | | Grafana Alloy | grafana/alloy | Apache-2.0 по умолчанию | diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index b3824e3..60c8088 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -50,11 +50,12 @@ 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 маршрута; ML он не запускает. - Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. - 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, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). +- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). +- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в backend нет Go клиента Kafka, топиков и проверки Kafka в readiness. - 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-приложение пока не отправляет телеметрию. -Еще не реализованы: регистрация и вход, согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Kafka/outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход, согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, transactional outbox и его relay, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы From 653f3775f80d0f2be3b3aaf2c1ca38faea245381 Mon Sep 17 00:00:00 2001 From: shira Date: Mon, 5 Oct 2026 22:57:19 +0300 Subject: [PATCH 005/143] feat(api): declare identity contract for registration, verification, and sessions --- api/README.en.md | 64 +- api/README.md | 64 +- api/core/components/examples.yml | 97 + api/core/components/headers.yml | 36 + api/core/components/responses.yml | 56 + api/core/components/schemas.yml | 242 ++ .../components/schemas/identity_schemas.yml | 283 +++ .../components/schemas/problem_schemas.yml | 10 + api/core/openapi.bundle.yml | 817 ++++++- api/core/openapi.yml | 93 + api/core/routes/identity_consent_texts.yml | 37 + .../identity_email_verification_requests.yml | 43 + .../routes/identity_email_verifications.yml | 47 + api/core/routes/identity_me.yml | 26 + api/core/routes/identity_registrations.yml | 67 + api/core/routes/identity_sessions.yml | 62 + api/core/routes/identity_sessions_current.yml | 60 + api/ml/components/schemas.yml | 10 +- api/ml/components/schemas/problem_schemas.yml | 7 + api/ml/openapi.bundle.yml | 7 + api/testdata/openapi-3.2.0.yml | 31 +- .../adapter/primary/http/api/oas_cfg_gen.go | 9 +- .../primary/http/api/oas_handlers_gen.go | 1461 ++++++++++++ .../primary/http/api/oas_interfaces_gen.go | 34 + .../adapter/primary/http/api/oas_json_gen.go | 2124 +++++++++++++++++ .../primary/http/api/oas_operations_gen.go | 10 +- .../primary/http/api/oas_parameters_gen.go | 183 ++ .../http/api/oas_request_decoders_gen.go | 328 +++ .../http/api/oas_response_encoders_gen.go | 562 +++++ .../primary/http/api/oas_router_gen.go | 546 ++++- .../primary/http/api/oas_schemas_gen.go | 1027 +++++++- .../primary/http/api/oas_security_gen.go | 150 ++ .../primary/http/api/oas_server_gen.go | 156 +- .../primary/http/api/oas_unimplemented_gen.go | 174 ++ .../primary/http/api/oas_validators_gen.go | 924 +++++++ .../adapter/primary/http/problem/problem.go | 25 + .../internal/adapter/primary/http/router.go | 6 +- .../adapter/primary/http/router_test.go | 311 ++- .../primary/http/security_contract_test.go | 80 + .../adapter/primary/http/v1/security.go | 70 + .../adapter/secondary/ml/api/oas_json_gen.go | 10 + .../secondary/ml/api/oas_schemas_gen.go | 68 +- .../secondary/ml/api/oas_validators_gen.go | 10 + backend/internal/bootstrap/wire.go | 2 + backend/internal/bootstrap/wire_gen.go | 3 +- docs/en/DEVELOPMENT.md | 8 +- docs/ru/DEVELOPMENT.md | 8 +- frontend/codegen/orval.config.ts | 10 + .../api/endpoints/identity/identity.msw.ts | 150 ++ .../shared/api/endpoints/identity/identity.ts | 821 +++++++ .../src/shared/api/endpoints/index.msw.ts | 1 + frontend/src/shared/api/endpoints/index.ts | 1 + .../src/shared/api/schemas/health/index.ts | 4 - .../api/schemas/health/problemCode.zod.ts | 12 - .../api/schemas/identity/account.zod.ts | 23 + .../schemas/identity/accountScenario.zod.ts | 12 + .../schemas/identity/confirmEmailBody.zod.ts | 20 + .../schemas/identity/consentPurpose.zod.ts | 12 + .../api/schemas/identity/consentText.zod.ts | 24 + .../identity/consentTextVersion.zod.ts | 17 + .../api/schemas/identity/csrfToken.zod.ts | 18 + .../api/schemas/identity/emailAddress.zod.ts | 16 + .../identity/emailVerificationRequest.zod.ts | 20 + .../emailVerificationResendRequest.zod.ts | 18 + .../identity/emailVerificationResult.zod.ts | 16 + .../identity/identityRequestAccepted.zod.ts | 14 + .../src/shared/api/schemas/identity/index.ts | 32 + .../api/schemas/identity/loginBody.zod.ts | 21 + .../api/schemas/identity/loginPassword.zod.ts | 15 + .../api/schemas/identity/loginRequest.zod.ts | 21 + .../api/schemas/identity/newPassword.zod.ts | 16 + .../schemas/identity/onboardingStep.zod.ts | 12 + .../personalDataConsentAcceptance.zod.ts | 20 + .../identity/registerAccountBody.zod.ts | 31 + .../identity/registerAccountHeaders.zod.ts | 19 + .../identity/registrationRequest.zod.ts | 31 + .../resendEmailVerificationBody.zod.ts | 18 + .../api/schemas/identity/session.zod.ts | 31 + .../schemas/{ => identity}/timestamp.zod.ts | 0 .../schemas/identity/verificationToken.zod.ts | 18 + frontend/src/shared/api/schemas/index.ts | 6 +- .../api/schemas/{health => }/problem.zod.ts | 2 +- .../src/shared/api/schemas/problemCode.zod.ts | 12 + .../{health => }/problemFieldError.zod.ts | 0 .../{health => }/problemFieldLocation.zod.ts | 0 ml/src/lincodex_ml/api/models.py | 12 +- 86 files changed, 11826 insertions(+), 148 deletions(-) create mode 100644 api/core/components/schemas/identity_schemas.yml create mode 100644 api/core/routes/identity_consent_texts.yml create mode 100644 api/core/routes/identity_email_verification_requests.yml create mode 100644 api/core/routes/identity_email_verifications.yml create mode 100644 api/core/routes/identity_me.yml create mode 100644 api/core/routes/identity_registrations.yml create mode 100644 api/core/routes/identity_sessions.yml create mode 100644 api/core/routes/identity_sessions_current.yml create mode 100644 backend/internal/adapter/primary/http/api/oas_interfaces_gen.go create mode 100644 backend/internal/adapter/primary/http/api/oas_parameters_gen.go create mode 100644 backend/internal/adapter/primary/http/api/oas_security_gen.go create mode 100644 backend/internal/adapter/primary/http/security_contract_test.go create mode 100644 backend/internal/adapter/primary/http/v1/security.go create mode 100644 frontend/src/shared/api/endpoints/identity/identity.msw.ts create mode 100644 frontend/src/shared/api/endpoints/identity/identity.ts delete mode 100644 frontend/src/shared/api/schemas/health/problemCode.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/account.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/accountScenario.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/confirmEmailBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/consentPurpose.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/consentText.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/consentTextVersion.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/csrfToken.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/emailAddress.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/emailVerificationRequest.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/emailVerificationResendRequest.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/emailVerificationResult.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/identityRequestAccepted.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/index.ts create mode 100644 frontend/src/shared/api/schemas/identity/loginBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/loginPassword.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/loginRequest.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/newPassword.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/onboardingStep.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/personalDataConsentAcceptance.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/registerAccountBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/registerAccountHeaders.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/registrationRequest.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/resendEmailVerificationBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/session.zod.ts rename frontend/src/shared/api/schemas/{ => identity}/timestamp.zod.ts (100%) create mode 100644 frontend/src/shared/api/schemas/identity/verificationToken.zod.ts rename frontend/src/shared/api/schemas/{health => }/problem.zod.ts (58%) create mode 100644 frontend/src/shared/api/schemas/problemCode.zod.ts rename frontend/src/shared/api/schemas/{health => }/problemFieldError.zod.ts (100%) rename frontend/src/shared/api/schemas/{health => }/problemFieldLocation.zod.ts (100%) diff --git a/api/README.en.md b/api/README.en.md index 97f60cf..b00115e 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -14,7 +14,7 @@ From the repository root, `make -C api check` checks contracts and `make generat ## Contract conventions -`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for future business operations; no public operation uses them yet. +`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation requires Idempotency-Key, but no operation stores keys yet. ### Errors @@ -23,8 +23,13 @@ Every error is an RFC 9457 problem with the `application/problem+json` media typ | Code | Status | Meaning | | --- | --- | --- | | `validation_failed` | 400 | Parameters or body do not match the contract, or the body violates a domain rule; `errors` lists the fields | +| `verification_token_invalid` | 400 | The email verification token is unknown, already used, or replaced | +| `verification_token_expired` | 400 | The email verification token is past its lifetime | | `unauthenticated` | 401 | No valid session | +| `invalid_credentials` | 401 | Login failed; an unknown email and a wrong password are not distinguished | | `forbidden` | 403 | The caller may not perform the operation | +| `email_not_verified` | 403 | Correct credentials, but the email is not verified | +| `csrf_check_failed` | 403 | Missing or wrong `X-CSRF-Token`, or a disallowed `Origin` | | `not_found` | 404 | Unknown route, or an object that does not exist or is not visible | | `method_not_allowed` | 405 | Unsupported method; see `Allow` | | `idempotency_in_progress` | 409 | A request with the same Idempotency-Key is still running | @@ -44,10 +49,14 @@ Request validation uses 400 rather than 422. The generated ogen server reports m Every operation declares `default: $ref: ../components/responses.yml#/Problem`; ogen then generates a single error type. An operation adds a specific response (for example `PreconditionFailed`) when clients need it in the generated types. In the Go API, unknown paths under `/api`, including paths outside `/api/v1`, answer 404 `not_found`, and a panic in an operation answers 500 `internal`; only the panic type and stack are logged. +Both verification token codes use 400 because the token is request content, not the target resource: 404 and 410 describe the URI, 409 a resource state, and 422 stays reserved for Idempotency-Key reuse. A malformed token fails schema validation and answers 400 `validation_failed` with the pointer `/token`. `invalid_credentials` and `unauthenticated` share 401 but mean a failed login and a missing session respectively. `email_not_verified` is returned only after the password matched, so it tells the verification state only to someone who already proved the password. + ### Retries and Idempotency-Key A mutating command declares the `IdempotencyKey` parameter. The client generates a key (a UUID v4 is recommended) and sends it in the `Idempotency-Key` header without quotes: 1-255 characters `A-Z a-z 0-9 . _ : -`. The server scopes the key by caller and operation and fingerprints the request by method, path, and body. +An anonymous operation defines its key scope and fingerprint in its own description; for `RegisterAccount` see the Identity section below. + Stored for 24 hours and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 `not_found` or 409 `state_conflict`. A replay does not repeat the side effect. Not stored, so a retry with the same key is evaluated again: 400 `validation_failed`, 413, and 415 for the request itself; 401 and 403; 409 `idempotency_in_progress`; 412 `version_conflict` and 428 `precondition_required` (nothing changed; read the resource again and retry); 422 `idempotency_key_reused`; 429; and every 5xx. @@ -76,7 +85,55 @@ Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with t ### ML service errors -The ML service answers its errors with the same `Problem` schema. FastAPI request validation answers 400 `validation_failed`. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, and 501 to their codes, 422 to 400 `validation_failed`, any other 4xx to 400 `validation_failed`, and any other 5xx to 500 `internal`. An unhandled exception answers 500 `internal` inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback. +The ML service answers its errors with the same `Problem` schema. Its `ProblemCode` enum keeps the public identity codes so both contracts share one shape, but the service never returns them. FastAPI request validation answers 400 `validation_failed`. An HTTP exception raised inside the service maps by status: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429, and 501 to their codes, 422 to 400 `validation_failed`, any other 4xx to 400 `validation_failed`, and any other 5xx to 500 `internal`. An unhandled exception answers 500 `internal` inside the application, so Starlette does not re-raise it to uvicorn; only its type is logged. The service also routes the uvicorn loggers through its JSON log format, which keeps only the exception type of a record and never its text or traceback. + +### Identity: sessions, cookie, and CSRF + +The `identity` tag covers registration, email verification, login, logout, and the current account. The operations are in the contract; their business logic is not implemented yet. Until it is, public operations answer 501 `not_implemented` after request validation, and the backend's `v1.DenyAllSecurity` rejects every session, so operations that require one answer 401 `unauthenticated`. Values marked as planned come from configuration in TASK-053 to TASK-056. + +| Method and path | operationId | Security | Success | Specific errors | +| --- | --- | --- | --- | --- | +| `GET /api/v1/identity/consent-texts/{purpose}` | `GetConsentText` | public | 200 `ConsentText` | 400 `validation_failed` | +| `POST /api/v1/identity/registrations` | `RegisterAccount` | public, Idempotency-Key | 202 `IdentityRequestAccepted` | 400 `validation_failed`, 403 `csrf_check_failed`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | +| `POST /api/v1/identity/email-verification-requests` | `ResendEmailVerification` | public | 202 `IdentityRequestAccepted` | 400, 403 `csrf_check_failed`, 429 | +| `POST /api/v1/identity/email-verifications` | `ConfirmEmail` | public | 200 `EmailVerificationResult` | 400 `verification_token_expired`, `verification_token_invalid`, or `validation_failed`; 403 `csrf_check_failed`; 429 | +| `POST /api/v1/identity/sessions` | `Login` | public | 201 `Session`, `Set-Cookie`, `Cache-Control: no-store` | 400, 401 `invalid_credentials`, 403 `email_not_verified` or `csrf_check_failed`, 429 | +| `GET /api/v1/identity/sessions/current` | `GetCurrentSession` | session | 200 `Session`, `Cache-Control: no-store` | 401 `unauthenticated` | +| `DELETE /api/v1/identity/sessions/current` | `Logout` | session and CSRF | 204, `Set-Cookie` clears the cookie | 401 `unauthenticated` (also clears the cookie), 403 `csrf_check_failed` | +| `GET /api/v1/identity/me` | `GetCurrentAccount` | session | 200 `Account`, `Cache-Control: no-store` | 401 `unauthenticated` | + +Every operation also declares the `default` problem response. + +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. +- 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. + +Consent C1 and the account: + +- `GetConsentText(c1)` returns the current C1 text, its `text_version`, and `published_at`. Registration sends that version in `consent_c1`; the server records it with the hash of the same stored text. A version that is no longer current answers 400 `validation_failed` with the pointer `/consent_c1/text_version`, and the client reads the text again. A dedicated code would trigger the same client action, and the field pointer already identifies it, so no new code is added. +- Unknown body fields are rejected, so no other consent, including C4, can be part of registration. +- Passwords are normalized to NFKC and must have 15-128 Unicode code points, without composition rules. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length. +- The account has a `scenario` (`candidate` or `employer`) and a saved `onboarding_step` that the server advances; after login the client returns the user to that step. Candidate steps are `candidate_consents`, `candidate_profile`, `candidate_questionnaire`, `candidate_assessment`, and `completed`; the employer has `employer_company` and `completed`. DTOs never contain password hashes, token hashes, or session identifiers. + +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 `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`. +- The root `security` requires `sessionCookie`, so an operation that does not declare `security: []` is protected by default. + +How the generated server (ogen v1.24.0) evaluates the schemes, and the mapping planned for TASK-056, are documented on `v1.DenyAllSecurity` and pinned by `TestGeneratedServerSecurityOrder`: + +- It calls `HandleSessionCookie` before `HandleSessionCsrf` and passes the context returned by a successful call on. An absent value (no cookie, empty `X-CSRF-Token`) does not call the handler, and a handler that returns `ogenerrors.ErrSkipServerSecurity` counts as unsatisfied; both continue with the next scheme, so `HandleSessionCsrf` also runs without a cookie, with the original context. +- Any other handler error stops evaluation and reaches `NewError` as a `SecurityError` whose `Security` is `SessionCookie` or `SessionCsrf`. An unsatisfied requirement reaches `NewError` as a `SecurityError` with `ErrSecurityRequirementIsNotSatisfied` and no `Security` field. +- Planned mapping: `HandleSessionCookie` skips a missing or invalid session; `HandleSessionCsrf` skips when the context has no principal (401) and returns a typed error for a wrong token. `NewError` maps a `SessionCsrf` error and an unsatisfied requirement with a principal in the context to 403 `csrf_check_failed`, and every other security failure to 401 `unauthenticated`. A 401 from `Logout` also clears the cookie. ### Generator checks @@ -100,5 +157,8 @@ Known generator limitations: - datamodel-code-generator 0.83.0 generates models only for schemas and query and path parameters; header parameters and response headers (Idempotency-Key, If-Match, ETag) produce no Python model. - Orval does not generate `additionalOperations` methods. - ogen writes the header name in its canonical Go form (`Etag`); HTTP header names are case-insensitive. +- ogen requires a `SecurityHandler` as soon as the contract has security schemes and evaluates the schemes in the order of their generated type names, so renaming a scheme can change the order; `TestGeneratedServerSecurityOrder` fails if it does. Security failures reach `NewError` without a response header, so clearing the cookie on a 401 from `Logout` needs handwritten code. +- Orval does not expose security scheme values as typed arguments, so `X-CSRF-Token` is not a generated parameter; the shared API client is planned to attach it to mutating requests. Orval also generates no type for `Set-Cookie`, which the browser handles. +- Orval clears `src/shared/api/endpoints/` and `src/shared/api/schemas/` before generation (`clean: true`), because a schema used by several tags moves from a tag directory to the schema root. See the [development guide](../docs/en/DEVELOPMENT.md). diff --git a/api/README.md b/api/README.md index bd56091..7b719d8 100644 --- a/api/README.md +++ b/api/README.md @@ -14,7 +14,7 @@ ## Соглашения контракта -`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение будущих бизнес-операций; ни одна публичная операция их пока не использует. +`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount` требует Idempotency-Key, но ни одна операция пока не хранит ключи. ### Ошибки @@ -23,8 +23,13 @@ | Код | Статус | Значение | | --- | --- | --- | | `validation_failed` | 400 | Параметры или тело не соответствуют контракту или тело нарушает доменное правило; `errors` перечисляет поля | +| `verification_token_invalid` | 400 | Токен подтверждения email неизвестен, уже использован или заменен | +| `verification_token_expired` | 400 | Срок действия токена подтверждения email истек | | `unauthenticated` | 401 | Нет действующей сессии | +| `invalid_credentials` | 401 | Вход не удался; неизвестный email и неверный пароль не различаются | | `forbidden` | 403 | Вызывающему запрещена операция | +| `email_not_verified` | 403 | Учетные данные верны, но email не подтвержден | +| `csrf_check_failed` | 403 | Нет или неверен `X-CSRF-Token`, либо `Origin` не разрешен | | `not_found` | 404 | Неизвестный маршрут или объект, который не существует или недоступен | | `method_not_allowed` | 405 | Метод не поддерживается; см. `Allow` | | `idempotency_in_progress` | 409 | Запрос с тем же Idempotency-Key еще выполняется | @@ -44,10 +49,14 @@ Каждая операция объявляет `default: $ref: ../components/responses.yml#/Problem`; тогда ogen генерирует единый тип ошибки. Конкретный ответ (например, `PreconditionFailed`) операция добавляет, когда он нужен клиентам в сгенерированных типах. В Go API неизвестные пути под `/api`, включая пути вне `/api/v1`, отвечают 404 `not_found`, а panic в операции - 500 `internal`; в лог попадают только тип panic и stack. +Оба кода токена подтверждения используют 400, потому что токен - содержимое запроса, а не целевой ресурс: 404 и 410 описывают URI, 409 - состояние ресурса, а 422 зарезервирован для повторного использования Idempotency-Key. Синтаксически неверный токен не проходит проверку схемы и дает 400 `validation_failed` с pointer `/token`. `invalid_credentials` и `unauthenticated` используют 401, но означают соответственно неудачный вход и отсутствие сессии. `email_not_verified` возвращается только после совпадения пароля, поэтому раскрывает состояние подтверждения только тому, кто уже доказал знание пароля. + ### Повторы и Idempotency-Key Изменяющая команда объявляет параметр `IdempotencyKey`. Клиент создает ключ (рекомендуется UUID v4) и передает его в заголовке `Idempotency-Key` без кавычек: 1-255 символов `A-Z a-z 0-9 . _ : -`. Сервер ограничивает ключ вызывающим и операцией и снимает отпечаток запроса по методу, пути и телу. +Анонимная операция сама определяет область ключа и отпечаток в своем описании; для `RegisterAccount` они описаны в разделе Identity ниже. + Хранятся 24 часа и воспроизводятся с теми же статусом, заголовками и телом: итоговый 2xx-результат и итоговые детерминированные бизнес-результаты 4xx, например 404 `not_found` или 409 `state_conflict`. Воспроизведение не повторяет побочный эффект. Не хранятся, поэтому повтор с тем же ключом обрабатывается заново: 400 `validation_failed`, 413 и 415 для самого запроса; 401 и 403; 409 `idempotency_in_progress`; 412 `version_conflict` и 428 `precondition_required` (ничего не изменилось; прочитайте ресурс снова и повторите); 422 `idempotency_key_reused`; 429; любой 5xx. @@ -76,7 +85,55 @@ ### Ошибки ML-сервиса -ML-сервис отвечает на ошибки той же схемой `Problem`. Валидация запроса FastAPI дает 400 `validation_failed`. HTTP-исключение внутри сервиса преобразуется по статусу: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429 и 501 - в свои коды, 422 - в 400 `validation_failed`, любой другой 4xx - в 400 `validation_failed`, любой другой 5xx - в 500 `internal`. Необработанное исключение дает 500 `internal` внутри приложения, поэтому Starlette не пробрасывает его в uvicorn; в лог попадает только тип. Сервис также направляет логгеры uvicorn через свой JSON-формат, который сохраняет только тип исключения записи, но не текст и не traceback. +ML-сервис отвечает на ошибки той же схемой `Problem`. Его перечисление `ProblemCode` сохраняет публичные коды identity, чтобы оба контракта имели одну форму, но сервис их никогда не возвращает. Валидация запроса FastAPI дает 400 `validation_failed`. HTTP-исключение внутри сервиса преобразуется по статусу: 400, 401, 403, 404, 405, 409 (`state_conflict`), 412, 413, 415, 428, 429 и 501 - в свои коды, 422 - в 400 `validation_failed`, любой другой 4xx - в 400 `validation_failed`, любой другой 5xx - в 500 `internal`. Необработанное исключение дает 500 `internal` внутри приложения, поэтому Starlette не пробрасывает его в uvicorn; в лог попадает только тип. Сервис также направляет логгеры uvicorn через свой JSON-формат, который сохраняет только тип исключения записи, но не текст и не traceback. + +### Identity: сессии, cookie и CSRF + +Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Операции есть в контракте, бизнес-логика еще не реализована. До ее появления публичные операции после валидации запроса отвечают 501 `not_implemented`, а `v1.DenyAllSecurity` в backend отклоняет любую сессию, поэтому операции, которым она нужна, отвечают 401 `unauthenticated`. Значения, отмеченные как запланированные, задаются конфигурацией в TASK-053 - TASK-056. + +| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | +| --- | --- | --- | --- | --- | +| `GET /api/v1/identity/consent-texts/{purpose}` | `GetConsentText` | публичная | 200 `ConsentText` | 400 `validation_failed` | +| `POST /api/v1/identity/registrations` | `RegisterAccount` | публичная, Idempotency-Key | 202 `IdentityRequestAccepted` | 400 `validation_failed`, 403 `csrf_check_failed`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | +| `POST /api/v1/identity/email-verification-requests` | `ResendEmailVerification` | публичная | 202 `IdentityRequestAccepted` | 400, 403 `csrf_check_failed`, 429 | +| `POST /api/v1/identity/email-verifications` | `ConfirmEmail` | публичная | 200 `EmailVerificationResult` | 400 `verification_token_expired`, `verification_token_invalid` или `validation_failed`; 403 `csrf_check_failed`; 429 | +| `POST /api/v1/identity/sessions` | `Login` | публичная | 201 `Session`, `Set-Cookie`, `Cache-Control: no-store` | 400, 401 `invalid_credentials`, 403 `email_not_verified` или `csrf_check_failed`, 429 | +| `GET /api/v1/identity/sessions/current` | `GetCurrentSession` | сессия | 200 `Session`, `Cache-Control: no-store` | 401 `unauthenticated` | +| `DELETE /api/v1/identity/sessions/current` | `Logout` | сессия и CSRF | 204, `Set-Cookie` удаляет cookie | 401 `unauthenticated` (тоже удаляет cookie), 403 `csrf_check_failed` | +| `GET /api/v1/identity/me` | `GetCurrentAccount` | сессия | 200 `Account`, `Cache-Control: no-store` | 401 `unauthenticated` | + +Каждая операция также объявляет problem-ответ `default`. + +Регистрация и подтверждение: + +- Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email, а вход отвечает 401 `invalid_credentials` и для неизвестного email, и для неверного пароля. +- До поиска email сервер проверяет все тело регистрации (длину пароля после нормализации NFKC, blocklist паролей, версию C1) и в каждой ветке вычисляет хеш Argon2id, поэтому ни 400, ни время ответа не зависят от существования аккаунта. +- Повторная регистрация неподтвержденного email заменяет хеш пароля, сценарий, шаг онбординга и запись C1, увеличивает версию регистрации, аннулирует все прежние токены подтверждения и отправляет новый. Поэтому предрегистрация с чужим паролем не переживает собственную регистрацию владельца адреса. Для подтвержденного email ничего не меняется; сервер может отправить ограниченное по частоте уведомление "у вас уже есть аккаунт". +- Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. +- Регистрация требует Idempotency-Key. Для этой анонимной операции ключ ограничивается операцией, самим ключом и HMAC нормализованного email; отпечаток - HMAC-SHA-256 с серверным секретом над каноническим JSON тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля. +- Ссылка подтверждения имеет вид `/verify-email#token=`. Страница удаляет фрагмент через `history.replaceState` и отправляет токен только после явного действия пользователя, поэтому токен не попадает в логи сервера и заголовок Referer, а сканер ссылок его не расходует. Подтверждение не создает сессию. +- Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии - `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку и вход. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос. + +Согласие C1 и аккаунт: + +- `GetConsentText(c1)` возвращает текущий текст C1, его `text_version` и `published_at`. Регистрация передает эту версию в `consent_c1`; сервер записывает ее вместе с хешем того же сохраненного текста. Версия, которая больше не текущая, дает 400 `validation_failed` с pointer `/consent_c1/text_version`, и клиент читает текст заново. Отдельный код вызвал бы то же действие клиента, а pointer поля уже указывает причину, поэтому новый код не добавлен. +- Неизвестные поля тела отклоняются, поэтому никакое другое согласие, включая C4, не может войти в регистрацию. +- Пароль нормализуется в NFKC и должен содержать от 15 до 128 кодовых точек Unicode, без правил состава. Сгенерированные Zod-валидаторы считают кодовые единицы UTF-16, поэтому длину окончательно проверяет сервер. +- У аккаунта есть `scenario` (`candidate` или `employer`) и сохраненный `onboarding_step`, который продвигает сервер; после входа клиент возвращает пользователя на этот шаг. Шаги кандидата: `candidate_consents`, `candidate_profile`, `candidate_questionnaire`, `candidate_assessment` и `completed`; у работодателя - `employer_company` и `completed`. DTO никогда не содержат хеши паролей, хеши токенов или идентификаторы сессий. + +Сессии и CSRF: + +- Схема `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`. +- Корневой `security` требует `sessionCookie`, поэтому операция без явного `security: []` защищена по умолчанию. + +Как сгенерированный сервер (ogen v1.24.0) проверяет схемы и какое отображение запланировано для TASK-056, описано в `v1.DenyAllSecurity` и закреплено тестом `TestGeneratedServerSecurityOrder`: + +- Он вызывает `HandleSessionCookie` раньше `HandleSessionCsrf` и передает дальше контекст, возвращенный успешным вызовом. Отсутствующее значение (нет cookie, пустой `X-CSRF-Token`) не вызывает обработчик, а обработчик, вернувший `ogenerrors.ErrSkipServerSecurity`, считается невыполненным; в обоих случаях проверка продолжается со следующей схемы, поэтому `HandleSessionCsrf` вызывается и без cookie, с исходным контекстом. +- Любая другая ошибка обработчика останавливает проверку и попадает в `NewError` как `SecurityError` с `Security`, равным `SessionCookie` или `SessionCsrf`. Невыполненное требование попадает в `NewError` как `SecurityError` с `ErrSecurityRequirementIsNotSatisfied` и без поля `Security`. +- Запланированное отображение: `HandleSessionCookie` пропускает отсутствующую или недействительную сессию; `HandleSessionCsrf` пропускает проверку, если в контексте нет principal (401), и возвращает типизированную ошибку при неверном токене. `NewError` отображает ошибку `SessionCsrf` и невыполненное требование с principal в контексте в 403 `csrf_check_failed`, а любой другой сбой защиты - в 401 `unauthenticated`. 401 от `Logout` также удаляет cookie. ### Проверки генераторов @@ -100,5 +157,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro - datamodel-code-generator 0.83.0 создает модели только для схем и query- и path-параметров; header-параметры и заголовки ответа (Idempotency-Key, If-Match, ETag) не дают Python-моделей. - Orval не генерирует методы для `additionalOperations`. - ogen записывает имя заголовка в канонической Go-форме (`Etag`); имена HTTP-заголовков не зависят от регистра. +- ogen требует `SecurityHandler`, как только в контракте есть схемы защиты, и проверяет схемы в порядке имен их сгенерированных типов, поэтому переименование схемы может изменить порядок; тогда `TestGeneratedServerSecurityOrder` упадет. Сбои защиты попадают в `NewError` без заголовков ответа, поэтому удаление cookie при 401 от `Logout` требует ручного кода. +- Orval не делает значения схем защиты типизированными аргументами, поэтому `X-CSRF-Token` не является сгенерированным параметром; его планируется добавлять к изменяющим запросам в общем API-клиенте. Тип для `Set-Cookie` Orval тоже не генерирует, этот заголовок обрабатывает браузер. +- Orval очищает `src/shared/api/endpoints/` и `src/shared/api/schemas/` перед генерацией (`clean: true`), потому что схема, используемая несколькими тегами, переезжает из каталога тега в корень схем. Подробнее: [разработка](../docs/ru/DEVELOPMENT.md). diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index a49ed3f..39ee1c9 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -138,3 +138,100 @@ NotImplemented: code: not_implemented detail: This operation is not available yet. trace_id: 0d1e2f3a-4b5c-4d6e-9f7a-8b9c0d1e2f3a +VerificationTokenInvalid: + summary: The verification token is unknown, used, or replaced + value: + type: urn:lincodex:problem:verification_token_invalid + title: Verification link is not valid + status: 400 + code: verification_token_invalid + detail: Request a new verification link, or sign in if the address is already verified. + trace_id: 3b4c5d6e-7f8a-4b9c-8d0e-1f2a3b4c5d6e +VerificationTokenExpired: + summary: The verification token is past its lifetime + value: + type: urn:lincodex:problem:verification_token_expired + title: Verification link expired + status: 400 + code: verification_token_expired + detail: Request a new verification link. + trace_id: 4c5d6e7f-8a9b-4c0d-9e1f-2a3b4c5d6e7f +VerificationTokenMalformed: + summary: The token from the link is malformed + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 5d6e7f8a-9b0c-4d1e-8f2a-3b4c5d6e7f8a + errors: + - in: body + pointer: /token + code: invalid + message: The value does not match the contract. +InvalidCredentials: + summary: Unknown email or wrong password + value: + type: urn:lincodex:problem:invalid_credentials + title: Invalid email or password + status: 401 + code: invalid_credentials + detail: Check the email and password and try again. + trace_id: 6e7f8a9b-0c1d-4e2f-9a3b-4c5d6e7f8a9b +EmailNotVerified: + summary: Correct credentials for an unverified email + value: + type: urn:lincodex:problem:email_not_verified + title: Email not verified + status: 403 + code: email_not_verified + detail: Confirm the email address with the link from the verification message. + trace_id: 7f8a9b0c-1d2e-4f3a-8b4c-5d6e7f8a9b0c +CsrfCheckFailed: + summary: Missing or wrong CSRF token, or a disallowed Origin + value: + type: urn:lincodex:problem:csrf_check_failed + title: Cross-site request check failed + status: 403 + code: csrf_check_failed + detail: Read the current session to get a new CSRF token and repeat the request. + trace_id: 8a9b0c1d-2e3f-4a4b-9c5d-6e7f8a9b0c1d +RegistrationValidationFailed: + summary: The password is too short and the consent text is outdated + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 9b0c1d2e-3f4a-4b5c-8d6e-7f8a9b0c1d2e + errors: + - in: body + pointer: /password + code: invalid + message: The value does not match the contract. + - in: body + pointer: /consent_c1/text_version + code: invalid + message: The value does not match the contract. +CandidateAccount: + summary: A verified candidate on the questionnaire step + value: + id: 0f8b6c2e-4d1a-4e7b-9c3f-5a2d8e6b1c47 + email: candidate@example.com + email_verified: true + scenario: candidate + onboarding_step: candidate_questionnaire + created_at: "2026-10-05T09:30:00Z" +CandidateSession: + summary: Session of a verified candidate + value: + account: + id: 0f8b6c2e-4d1a-4e7b-9c3f-5a2d8e6b1c47 + email: candidate@example.com + email_verified: true + scenario: candidate + onboarding_step: candidate_questionnaire + created_at: "2026-10-05T09:30:00Z" + csrf_token: Xk4pR9tV2mQ7wL1sN8bC5dF0gH3jZ6yA9eU2iO7rT4c diff --git a/api/core/components/headers.yml b/api/core/components/headers.yml index 6f30714..750a842 100644 --- a/api/core/components/headers.yml +++ b/api/core/components/headers.yml @@ -17,3 +17,39 @@ RetryAfter: minimum: 0 maximum: 86400 example: 30 +SessionCookieSet: + description: >- + Sets the session cookie `__Host-lincodex_session` with an opaque random + value and the attributes `Path=/; Secure; HttpOnly; SameSite=Strict` and + no Domain. The `__Host-` prefix makes the browser reject the cookie + without Secure and Path=/ or with a Domain. Max-Age equals the remaining + absolute session lifetime. The value is never readable by scripts or present in a + body. + required: true + schema: + type: string + minLength: 1 + maxLength: 4096 + pattern: "^__Host-lincodex_session=" + example: __Host-lincodex_session=opaque-session-value; Path=/; Max-Age=604800; Secure; HttpOnly; SameSite=Strict +SessionCookieCleared: + description: >- + Removes the session cookie with an empty value, `Max-Age=0`, and the + same attributes it was set with. + required: true + schema: + type: string + minLength: 1 + maxLength: 4096 + pattern: "^__Host-lincodex_session=" + example: __Host-lincodex_session=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=Strict +CacheControlNoStore: + description: >- + `no-store`: the response carries account or session data that browsers + and intermediaries must not keep. + required: true + schema: + type: string + enum: + - no-store + example: no-store diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml index 96032ea..55d2d58 100644 --- a/api/core/components/responses.yml +++ b/api/core/components/responses.yml @@ -157,3 +157,59 @@ Problem: $ref: ./examples.yml#/Internal not_implemented: $ref: ./examples.yml#/NotImplemented +RegistrationValidationFailed: + description: >- + The body does not match the contract or violates a registration rule: + a password outside 15-128 characters or on the blocklist, or a consent + text version that is not the current one; code validation_failed with + body pointers. An email that already belongs to an account is never a + validation error. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + validation_failed: + $ref: ./examples.yml#/RegistrationValidationFailed +EmailVerificationFailed: + description: >- + The token cannot verify an email. Code verification_token_expired means + the token is past its lifetime; verification_token_invalid means it is + unknown, already used, or replaced by a newer link; validation_failed + with the pointer `/token` means the token is malformed. Nothing was + changed in any case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + verification_token_expired: + $ref: ./examples.yml#/VerificationTokenExpired + verification_token_invalid: + $ref: ./examples.yml#/VerificationTokenInvalid + validation_failed: + $ref: ./examples.yml#/VerificationTokenMalformed +InvalidCredentials: + description: >- + The email and password do not match an account; code + invalid_credentials. An unknown email and a wrong password get the same + response. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + invalid_credentials: + $ref: ./examples.yml#/InvalidCredentials +CsrfCheckFailed: + description: >- + The request failed cross-site request protection: the X-CSRF-Token + header is missing or does not belong to the session, or the Origin is + not allowed; code csrf_check_failed. Nothing was changed. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + csrf_check_failed: + $ref: ./examples.yml#/CsrfCheckFailed diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index 5dce273..a364207 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -33,6 +33,233 @@ HealthResponse: type: string enum: - ok +EmailAddress: + type: string + format: email + minLength: 3 + maxLength: 254 + description: Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account. + examples: + - candidate@example.com +NewPassword: + type: string + minLength: 15 + maxLength: 128 + description: Password chosen at registration. The server normalizes it to Unicode NFKC, as NIST SP 800-63B-4 recommends, and then requires 15 to 128 Unicode code points; a value that the schema accepts can still fail this check after normalization. The 15-character minimum follows NIST SP 800-63B-4 for a password used as the only authentication factor; there are no composition rules. The upper bound limits the cost of password hashing. Generated client validators count UTF-16 code units, so a password with characters outside the Basic Multilingual Plane can pass the client check and fail on the server; a later client check should count code points. A password on the server blocklist of common or breached passwords answers 400 validation_failed with the pointer `/password`. The value is never returned, logged, or echoed in a problem. +LoginPassword: + type: string + minLength: 1 + maxLength: 128 + description: Password entered at login. The server applies the same NFKC normalization as at registration before it verifies the hash. Only the hashing bound applies, so a later change of the registration policy does not lock out existing accounts and a login error does not reveal the policy. The value is never returned, logged, or echoed in a problem. +AccountScenario: + type: string + description: 'Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, `employer` represents a company that searches for candidates. The scenario selects the onboarding steps.' + enum: + - candidate + - employer +OnboardingStep: + type: string + description: 'Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly. + + + - candidate_consents: candidate consents beyond C1, which was given at registration. + + - candidate_profile: candidate profile. + + - candidate_questionnaire: candidate questionnaire. + + - candidate_assessment: choice of the expected grade and the assessment. + + - employer_company: company profile of the employer. + + - completed: onboarding is finished; the client opens the scenario home. + + + Candidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.' + enum: + - candidate_consents + - candidate_profile + - candidate_questionnaire + - candidate_assessment + - employer_company + - completed +ConsentPurpose: + type: string + description: 'Consent whose text the client may read before an account exists. Only the consents given at registration are listed: `c1` is the consent to the processing of personal data.' + enum: + - c1 +ConsentText: + type: object + description: Currently published consent text. The server stores an acceptance with `text_version` and the hash of exactly this text. + additionalProperties: false + required: + - purpose + - text_version + - text + - published_at + properties: + purpose: + $ref: '#/ConsentPurpose' + text_version: + $ref: '#/ConsentTextVersion' + text: + type: string + minLength: 1 + maxLength: 100000 + description: Full consent text in plain UTF-8; paragraphs are separated by an empty line. The client shows it as text, never as HTML. + published_at: + $ref: '#/Timestamp' +ConsentTextVersion: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9._-]+$ + description: Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash. + examples: + - c1-2026-10-01 +PersonalDataConsentAcceptance: + type: object + description: Consent C1 to the processing of personal data, given at registration. The client reads the current text and its version with GetConsentText(c1) and sends that version here. A version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c1/text_version`; the client then reads the text again and asks the user to accept the new version. Unknown fields are rejected, so registration cannot carry any other consent; in particular, C4 is never part of registration. + additionalProperties: false + required: + - text_version + - accepted + properties: + text_version: + $ref: '#/ConsentTextVersion' + accepted: + type: boolean + enum: + - true + description: Explicit acceptance. Only true is valid. +RegistrationRequest: + type: object + description: New account with its scenario and consent C1. + additionalProperties: false + required: + - email + - password + - scenario + - consent_c1 + properties: + email: + $ref: '#/EmailAddress' + password: + $ref: '#/NewPassword' + scenario: + $ref: '#/AccountScenario' + consent_c1: + $ref: '#/PersonalDataConsentAcceptance' +EmailVerificationResendRequest: + type: object + description: Address that should receive a new verification link. + additionalProperties: false + required: + - email + properties: + email: + $ref: '#/EmailAddress' +IdentityRequestAccepted: + type: object + description: Neutral acknowledgement. Its content is identical whether or not the address belongs to an account or is already verified, so the response does not enumerate accounts. The client tells the user to check the mailbox. + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - accepted +VerificationToken: + type: string + minLength: 32 + maxLength: 128 + pattern: ^[A-Za-z0-9_-]+$ + description: 'One-time raw token copied from the verification link. It is request input only: the server stores only its hash and never returns a token.' +EmailVerificationRequest: + type: object + description: Token from the email verification link. + additionalProperties: false + required: + - token + properties: + token: + $ref: '#/VerificationToken' +EmailVerificationResult: + type: object + description: Result of a successful email verification. It does not start a session; the user signs in next and continues from `onboarding_step`. + additionalProperties: false + required: + - email_verified + - scenario + - onboarding_step + properties: + email_verified: + type: boolean + enum: + - true + description: Always true in a successful response. + scenario: + $ref: '#/AccountScenario' + onboarding_step: + $ref: '#/OnboardingStep' +LoginRequest: + type: object + description: Email and password of the account. + additionalProperties: false + required: + - email + - password + properties: + email: + $ref: '#/EmailAddress' + password: + $ref: '#/LoginPassword' +CsrfToken: + type: string + minLength: 32 + maxLength: 128 + pattern: ^[A-Za-z0-9_-]+$ + description: CSRF token bound to the current session. The client keeps it in memory only and sends it in the X-CSRF-Token header of every mutating request that requires a session. It changes when a new session starts. +Account: + type: object + description: Current account view. It never contains password hashes, token hashes, session identifiers, or other storage secrets. + additionalProperties: false + required: + - id + - email + - email_verified + - scenario + - onboarding_step + - created_at + properties: + id: + type: string + format: uuid + description: Account identifier. + email: + $ref: '#/EmailAddress' + email_verified: + type: boolean + description: Whether the address is verified. A session exists only for a verified account, so this is true in every current response. + scenario: + $ref: '#/AccountScenario' + onboarding_step: + $ref: '#/OnboardingStep' + created_at: + $ref: '#/Timestamp' +Session: + type: object + description: 'Current session as the client may see it: the account and the CSRF token. The session identifier itself travels only in the HttpOnly session cookie and never appears in a body.' + additionalProperties: false + required: + - account + - csrf_token + properties: + account: + $ref: '#/Account' + csrf_token: + $ref: '#/CsrfToken' Problem: type: object description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. @@ -89,10 +316,20 @@ ProblemCode: - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - verification_token_invalid (400): the email verification token is unknown, already used, or replaced by a newer one; request a new link or sign in. + + - verification_token_expired (400): the email verification token is past its lifetime; request a new link. + - unauthenticated (401): no valid session or credentials. + - invalid_credentials (401): the email and password do not match an account; an unknown email and a wrong password are not distinguished. + - forbidden (403): the caller is authenticated but not allowed. + - email_not_verified (403): the credentials are correct but the email is not verified yet. + + - csrf_check_failed (403): the request failed cross-site request protection: a missing or wrong X-CSRF-Token or a disallowed Origin. + - not_found (404): the route or object does not exist or is not visible. - method_not_allowed (405): the route does not support the method. @@ -118,8 +355,13 @@ ProblemCode: - not_implemented (501): the operation is in the contract but not implemented yet.' enum: - validation_failed + - verification_token_invalid + - verification_token_expired - unauthenticated + - invalid_credentials - forbidden + - email_not_verified + - csrf_check_failed - not_found - method_not_allowed - idempotency_in_progress diff --git a/api/core/components/schemas/identity_schemas.yml b/api/core/components/schemas/identity_schemas.yml new file mode 100644 index 0000000..f2e3259 --- /dev/null +++ b/api/core/components/schemas/identity_schemas.yml @@ -0,0 +1,283 @@ +schemas: + EmailAddress: + type: string + format: email + minLength: 3 + maxLength: 254 + description: >- + Account email address. The server compares addresses without regard to + letter case and never reveals in a response whether an address belongs + to an account. + examples: + - candidate@example.com + NewPassword: + type: string + minLength: 15 + maxLength: 128 + description: >- + Password chosen at registration. The server normalizes it to Unicode + NFKC, as NIST SP 800-63B-4 recommends, and then requires 15 to 128 Unicode + code points; a value that the schema accepts can still fail this check + after normalization. The 15-character minimum follows NIST SP + 800-63B-4 for a password used as the only authentication factor; there + are no composition rules. The upper bound limits the cost of password + hashing. Generated client validators count UTF-16 code units, so a + password with characters outside the Basic Multilingual Plane can pass + the client check and fail on the server; a later client check should + count code points. A password on the server blocklist of common or + breached passwords answers 400 validation_failed with the pointer + `/password`. The value is never returned, logged, or echoed in a + problem. + LoginPassword: + type: string + minLength: 1 + maxLength: 128 + description: >- + Password entered at login. The server applies the same NFKC + normalization as at registration before it verifies the hash. Only the + hashing bound applies, so a later change of the registration policy + does not lock out existing accounts and a login error does not reveal + the policy. The value is never returned, logged, or echoed in a + problem. + AccountScenario: + type: string + description: >- + Scenario chosen at registration: `candidate` looks for an offer and + passes the assessment, `employer` represents a company that searches + for candidates. The scenario selects the onboarding steps. + enum: + - candidate + - employer + OnboardingStep: + type: string + description: |- + Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly. + + - candidate_consents: candidate consents beyond C1, which was given at registration. + - candidate_profile: candidate profile. + - candidate_questionnaire: candidate questionnaire. + - candidate_assessment: choice of the expected grade and the assessment. + - employer_company: company profile of the employer. + - completed: onboarding is finished; the client opens the scenario home. + + Candidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change. + enum: + - candidate_consents + - candidate_profile + - candidate_questionnaire + - candidate_assessment + - employer_company + - completed + ConsentPurpose: + type: string + description: >- + Consent whose text the client may read before an account exists. Only + the consents given at registration are listed: `c1` is the consent to + the processing of personal data. + enum: + - c1 + ConsentText: + type: object + description: >- + Currently published consent text. The server stores an acceptance with + `text_version` and the hash of exactly this text. + additionalProperties: false + required: + - purpose + - text_version + - text + - published_at + properties: + purpose: + $ref: "#/schemas/ConsentPurpose" + text_version: + $ref: "#/schemas/ConsentTextVersion" + text: + type: string + minLength: 1 + maxLength: 100000 + description: >- + Full consent text in plain UTF-8; paragraphs are separated by an + empty line. The client shows it as text, never as HTML. + published_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + ConsentTextVersion: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Identifier of the published consent text that the user saw and + accepted. The server stores the acceptance with this version and the + hash of its text; the client never sends or receives the hash. + examples: + - c1-2026-10-01 + PersonalDataConsentAcceptance: + type: object + description: >- + Consent C1 to the processing of personal data, given at registration. + The client reads the current text and its version with + GetConsentText(c1) and sends that version here. A version that is not + the currently published one answers 400 validation_failed with the + pointer `/consent_c1/text_version`; the client then reads the text + again and asks the user to accept the new version. Unknown fields are + rejected, so registration cannot carry any other consent; in + particular, C4 is never part of registration. + additionalProperties: false + required: + - text_version + - accepted + properties: + text_version: + $ref: "#/schemas/ConsentTextVersion" + accepted: + type: boolean + enum: + - true + description: Explicit acceptance. Only true is valid. + RegistrationRequest: + type: object + description: New account with its scenario and consent C1. + additionalProperties: false + required: + - email + - password + - scenario + - consent_c1 + properties: + email: + $ref: "#/schemas/EmailAddress" + password: + $ref: "#/schemas/NewPassword" + scenario: + $ref: "#/schemas/AccountScenario" + consent_c1: + $ref: "#/schemas/PersonalDataConsentAcceptance" + EmailVerificationResendRequest: + type: object + description: Address that should receive a new verification link. + additionalProperties: false + required: + - email + properties: + email: + $ref: "#/schemas/EmailAddress" + IdentityRequestAccepted: + type: object + description: >- + Neutral acknowledgement. Its content is identical whether or not the + address belongs to an account or is already verified, so the response + does not enumerate accounts. The client tells the user to check the + mailbox. + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - accepted + VerificationToken: + type: string + minLength: 32 + maxLength: 128 + pattern: "^[A-Za-z0-9_-]+$" + description: >- + One-time raw token copied from the verification link. It is request + input only: the server stores only its hash and never returns a token. + EmailVerificationRequest: + type: object + description: Token from the email verification link. + additionalProperties: false + required: + - token + properties: + token: + $ref: "#/schemas/VerificationToken" + EmailVerificationResult: + type: object + description: >- + Result of a successful email verification. It does not start a + session; the user signs in next and continues from `onboarding_step`. + additionalProperties: false + required: + - email_verified + - scenario + - onboarding_step + properties: + email_verified: + type: boolean + enum: + - true + description: Always true in a successful response. + scenario: + $ref: "#/schemas/AccountScenario" + onboarding_step: + $ref: "#/schemas/OnboardingStep" + LoginRequest: + type: object + description: Email and password of the account. + additionalProperties: false + required: + - email + - password + properties: + email: + $ref: "#/schemas/EmailAddress" + password: + $ref: "#/schemas/LoginPassword" + CsrfToken: + type: string + minLength: 32 + maxLength: 128 + pattern: "^[A-Za-z0-9_-]+$" + description: >- + CSRF token bound to the current session. The client keeps it in memory + only and sends it in the X-CSRF-Token header of every mutating request + that requires a session. It changes when a new session starts. + Account: + type: object + description: >- + Current account view. It never contains password hashes, token hashes, + session identifiers, or other storage secrets. + additionalProperties: false + required: + - id + - email + - email_verified + - scenario + - onboarding_step + - created_at + properties: + id: + type: string + format: uuid + description: Account identifier. + email: + $ref: "#/schemas/EmailAddress" + email_verified: + type: boolean + description: >- + Whether the address is verified. A session exists only for a + verified account, so this is true in every current response. + scenario: + $ref: "#/schemas/AccountScenario" + onboarding_step: + $ref: "#/schemas/OnboardingStep" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + Session: + type: object + description: >- + Current session as the client may see it: the account and the CSRF + token. The session identifier itself travels only in the HttpOnly + session cookie and never appears in a body. + additionalProperties: false + required: + - account + - csrf_token + properties: + account: + $ref: "#/schemas/Account" + csrf_token: + $ref: "#/schemas/CsrfToken" diff --git a/api/core/components/schemas/problem_schemas.yml b/api/core/components/schemas/problem_schemas.yml index dba3601..72cde46 100644 --- a/api/core/components/schemas/problem_schemas.yml +++ b/api/core/components/schemas/problem_schemas.yml @@ -70,8 +70,13 @@ schemas: Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - verification_token_invalid (400): the email verification token is unknown, already used, or replaced by a newer one; request a new link or sign in. + - verification_token_expired (400): the email verification token is past its lifetime; request a new link. - unauthenticated (401): no valid session or credentials. + - invalid_credentials (401): the email and password do not match an account; an unknown email and a wrong password are not distinguished. - forbidden (403): the caller is authenticated but not allowed. + - email_not_verified (403): the credentials are correct but the email is not verified yet. + - csrf_check_failed (403): the request failed cross-site request protection: a missing or wrong X-CSRF-Token or a disallowed Origin. - not_found (404): the route or object does not exist or is not visible. - method_not_allowed (405): the route does not support the method. - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. @@ -86,8 +91,13 @@ schemas: - not_implemented (501): the operation is in the contract but not implemented yet. enum: - validation_failed + - verification_token_invalid + - verification_token_expired - unauthenticated + - invalid_credentials - forbidden + - email_not_verified + - csrf_check_failed - not_found - method_not_allowed - idempotency_in_progress diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 1d8ff51..629cdfe 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -4,6 +4,13 @@ info: version: 0.1.0 servers: - url: / +security: + - sessionCookie: [] +tags: + - name: health + description: Liveness of the API process. + - name: identity + description: Registration, email verification, login, logout, and the current account. Sessions are server-side and travel in an HttpOnly cookie; mutating requests that require a session also carry a CSRF token. paths: /api/v1/healthz: get: @@ -26,6 +33,342 @@ paths: status: ok default: $ref: '#/components/responses/Problem' + /api/v1/identity/consent-texts/{purpose}: + get: + operationId: GetConsentText + summary: Read the currently published text of a registration consent. + description: Public operation without a session. Returns the current text of a consent that is given before an account exists; only `c1` is available. The registration page shows this text and sends its `text_version` with RegisterAccount, and the server hashes the same stored text when it records the acceptance. If the text changes while the page is open, RegisterAccount answers 400 validation_failed with the pointer `/consent_c1/text_version`, and the page reads the text again. An unknown purpose fails parameter validation with 400. + security: [] + tags: + - identity + parameters: + - name: purpose + in: path + required: true + description: Consent whose text is requested. + schema: + $ref: '#/components/schemas/ConsentPurpose' + responses: + '200': + description: The current consent text. + content: + application/json: + schema: + $ref: '#/components/schemas/ConsentText' + examples: + c1: + summary: Current C1 text + value: + purpose: c1 + text_version: c1-2026-10-01 + text: |- + I consent to the processing of my personal data for registration and the use of the service. + + The full text is published by the operator. + published_at: '2026-10-01T00:00:00Z' + '400': + $ref: '#/components/responses/ValidationFailed' + default: + $ref: '#/components/responses/Problem' + /api/v1/identity/registrations: + post: + operationId: RegisterAccount + summary: Register an account by email with a scenario and consent C1. + description: |- + Public operation without a session. The client reads the current C1 text with GetConsentText and sends the email, the password, the chosen scenario, and consent C1 with the version of the text the user accepted. + + The answer is the same 202 whether the email is new, registered but not verified, or verified, so registration does not enumerate accounts: + + - New email: the server creates an unverified account with the scenario and the first onboarding step, records C1 with its text version and text hash, stores only the hash of a one-time verification token, and queues the verification message, all in one transaction. + - Registered but not verified: the server treats the request as a new registration of that address. In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1 record, advances the registration version, invalidates every earlier verification token, and queues a message with a new token. A pre-registration with someone else's password therefore never survives the address owner's own registration. + - Verified: nothing changes. The server may queue a rate-limited "you already have an account" notice to the address. + + Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration can never confirm the newer credentials. An account that stays unverified is deleted with its consent record and tokens 7 days after its last registration (planned value from configuration). Verification tokens live 24 hours (planned value from configuration). + + The response does not depend on the branch in content or timing. Before it looks up the email, the server validates the whole body, including the password bounds after normalization, the password blocklist, and the C1 version, and it computes the Argon2id hash on every branch; a 400 therefore never depends on whether the email exists. Mail is delivered asynchronously from the outbox. + + The operation requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email, and the request fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The server never stores the body, the password, or a plain hash of either; the secret keeps the fingerprint from serving as an offline password check. A retry with the same key, email, and body replays the stored 202 without a second message; the same key and email with a different body answers 422 idempotency_key_reused. + + It is rate-limited per client and per email and answers 429 with Retry-After when the limit is reached. Like every unsafe request, it requires an allowed Origin and answers 403 csrf_check_failed otherwise. + security: [] + tags: + - identity + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RegistrationRequest' + examples: + candidate: + summary: Candidate registration + value: + email: candidate@example.com + password: correct horse battery staple + scenario: candidate + consent_c1: + text_version: c1-2026-10-01 + accepted: true + responses: + '202': + description: Registration request accepted. If the email can be registered, a verification link is on its way; the response does not say whether it was. + content: + application/json: + schema: + $ref: '#/components/schemas/IdentityRequestAccepted' + examples: + accepted: + summary: Neutral acknowledgement + value: + status: accepted + '400': + $ref: '#/components/responses/RegistrationValidationFailed' + '403': + $ref: '#/components/responses/CsrfCheckFailed' + '409': + $ref: '#/components/responses/IdempotencyInProgress' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/identity/email-verification-requests: + post: + operationId: ResendEmailVerification + summary: Request a new email verification link. + description: |- + Public operation without a session. The answer is the same 202 for an unknown email, a verified email, and an unverified one, so it does not enumerate accounts. Only for an unverified account does the server issue a new one-time token bound to the current registration version, invalidate every earlier token of that account, and queue the message. Resend never changes the password, the scenario, or the consent record; a user who did not start the pending registration registers again instead, which replaces it. + + It is rate-limited per client and per email and answers 429 with Retry-After when the limit is reached. A retry is safe without Idempotency-Key: at worst it replaces the token again within the rate limit. Like every unsafe request, it requires an allowed Origin and answers 403 csrf_check_failed otherwise. + security: [] + tags: + - identity + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EmailVerificationResendRequest' + examples: + resend: + summary: Resend to an address + value: + email: candidate@example.com + responses: + '202': + description: Request accepted. If the address belongs to an unverified account, a new link is on its way; the response does not say whether it was. + content: + application/json: + schema: + $ref: '#/components/schemas/IdentityRequestAccepted' + examples: + accepted: + summary: Neutral acknowledgement + value: + status: accepted + '400': + $ref: '#/components/responses/ValidationFailed' + '403': + $ref: '#/components/responses/CsrfCheckFailed' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/identity/email-verifications: + post: + operationId: ConfirmEmail + summary: Verify an email with the one-time token from the link. + description: |- + Public operation without a session. The verification link has the form `/verify-email#token=`: the token travels in the URL fragment, so it never reaches a server log or a Referer header. The page first removes the fragment with `history.replaceState`, then waits for an explicit user action, such as a Confirm button, before it posts the token here. A link scanner that only fetches the page therefore does not consume the token. + + The server looks up the token by its hash and, in one transaction, checks that it is unused, not expired, and bound to the current registration version, marks it used, and marks the email verified. Only one of several parallel requests with the same token succeeds. An expired token answers verification_token_expired; an unknown, used, replaced, or superseded token answers verification_token_invalid; neither changes anything. For both, the client offers a new link and sign-in, because the address may already be verified. + + A repeated confirmation with an already used token is not an idempotent 200: exactly one request may succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after either outcome is sign-in anyway. + + Success does not start a session: the link may be opened on another device or by a mail scanner, and a session must come only from the password. The response returns the scenario and the saved onboarding step so the client can continue after sign-in. The operation is rate-limited and requires an allowed Origin. + security: [] + tags: + - identity + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EmailVerificationRequest' + examples: + token: + summary: Token from the link + value: + token: q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE + responses: + '200': + description: The email is verified. + content: + application/json: + schema: + $ref: '#/components/schemas/EmailVerificationResult' + examples: + candidate: + summary: A candidate continues with consents + value: + email_verified: true + scenario: candidate + onboarding_step: candidate_consents + '400': + $ref: '#/components/responses/EmailVerificationFailed' + '403': + $ref: '#/components/responses/CsrfCheckFailed' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/identity/sessions: + post: + operationId: Login + summary: Sign in with email and password and start a session. + description: |- + Public operation that starts a server session. The server verifies the password with Argon2id; for an unknown email it verifies against a fixed dummy hash, so the response time does not reveal whether the account exists. An unknown email and a wrong password both answer 401 invalid_credentials. + + Correct credentials for an unverified email answer 403 email_not_verified and create no session. This reveals the verification state only to someone who already knows the password, which proves more than the state itself; the client offers to resend the link. + + On success the server revokes the session that the request carried, if any, creates a new random session in PostgreSQL with a new identifier and a new CSRF token, sets the HttpOnly session cookie, and returns the account and the CSRF token. The new session follows the idle and absolute timeouts of the sessionCookie scheme. The client keeps the token in memory and sends it in X-CSRF-Token with every mutating request that requires a session. + + Login is rate-limited per client and per email and answers 429 with Retry-After. Like every unsafe request, it requires an allowed Origin, which protects against login CSRF, and answers 403 csrf_check_failed otherwise. + security: [] + tags: + - identity + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/LoginRequest' + examples: + login: + summary: Email and password + value: + email: candidate@example.com + password: correct horse battery staple + responses: + '201': + description: Session started; the session cookie is set. + headers: + Set-Cookie: + $ref: '#/components/headers/SessionCookieSet' + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/Session' + examples: + candidate: + $ref: '#/components/examples/CandidateSession' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/InvalidCredentials' + '403': + description: Correct credentials for an unverified email (email_not_verified), or a disallowed Origin (csrf_check_failed). No session was created. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + email_not_verified: + $ref: '#/components/examples/EmailNotVerified' + csrf_check_failed: + $ref: '#/components/examples/CsrfCheckFailed' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/identity/sessions/current: + get: + operationId: GetCurrentSession + summary: Read the current session and its CSRF token. + description: Requires the session cookie. Returns the account and the CSRF token of the current session, so the client can restore the token after a page reload or after 403 csrf_check_failed. A missing, unknown, expired, or revoked session answers 401 unauthenticated. Cross-origin pages cannot read the token, because the API sends no Access-Control-Allow-Origin header. + security: + - sessionCookie: [] + tags: + - identity + responses: + '200': + description: The current session. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/Session' + examples: + candidate: + $ref: '#/components/examples/CandidateSession' + '401': + $ref: '#/components/responses/Unauthenticated' + default: + $ref: '#/components/responses/Problem' + delete: + operationId: Logout + summary: Sign out and revoke the current session. + description: Requires the session cookie and the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The server revokes the session in PostgreSQL, so the cookie value stops working even if a copy remains, and clears the cookie. A missing, expired, or revoked session answers 401 unauthenticated and also clears the cookie, so a stale cookie does not stay in the browser; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed and keeps the session and the cookie. The client clears its private query cache after the response. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - identity + responses: + '204': + description: The session is revoked and the cookie is cleared. + headers: + Set-Cookie: + $ref: '#/components/headers/SessionCookieCleared' + '401': + description: No valid session; code unauthenticated. The cookie is cleared as well. + headers: + Set-Cookie: + $ref: '#/components/headers/SessionCookieCleared' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + unauthenticated: + $ref: '#/components/examples/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailed' + default: + $ref: '#/components/responses/Problem' + /api/v1/identity/me: + get: + operationId: GetCurrentAccount + summary: Read the account of the current session. + description: Requires the session cookie. The account comes from the session, never from a request parameter. The client uses `scenario` and `onboarding_step` to return the user to the unfinished onboarding step. A missing, unknown, expired, or revoked session answers 401 unauthenticated. An unverified account never has a session, because login answers 403 email_not_verified for it, so this operation also answers 401 for such an account. + security: + - sessionCookie: [] + tags: + - identity + responses: + '200': + description: The current account. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/Account' + examples: + candidate: + $ref: '#/components/examples/CandidateAccount' + '401': + $ref: '#/components/responses/Unauthenticated' + default: + $ref: '#/components/responses/Problem' components: schemas: Problem: @@ -83,8 +426,13 @@ components: Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - verification_token_invalid (400): the email verification token is unknown, already used, or replaced by a newer one; request a new link or sign in. + - verification_token_expired (400): the email verification token is past its lifetime; request a new link. - unauthenticated (401): no valid session or credentials. + - invalid_credentials (401): the email and password do not match an account; an unknown email and a wrong password are not distinguished. - forbidden (403): the caller is authenticated but not allowed. + - email_not_verified (403): the credentials are correct but the email is not verified yet. + - csrf_check_failed (403): the request failed cross-site request protection: a missing or wrong X-CSRF-Token or a disallowed Origin. - not_found (404): the route or object does not exist or is not visible. - method_not_allowed (405): the route does not support the method. - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. @@ -99,8 +447,13 @@ components: - not_implemented (501): the operation is in the contract but not implemented yet. enum: - validation_failed + - verification_token_invalid + - verification_token_expired - unauthenticated + - invalid_credentials - forbidden + - email_not_verified + - csrf_check_failed - not_found - method_not_allowed - idempotency_in_progress @@ -175,6 +528,227 @@ components: maxLength: 512 pattern: ^[A-Za-z0-9_-]+$ description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing. + EmailAddress: + type: string + format: email + minLength: 3 + maxLength: 254 + description: Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account. + examples: + - candidate@example.com + NewPassword: + type: string + minLength: 15 + maxLength: 128 + description: Password chosen at registration. The server normalizes it to Unicode NFKC, as NIST SP 800-63B-4 recommends, and then requires 15 to 128 Unicode code points; a value that the schema accepts can still fail this check after normalization. The 15-character minimum follows NIST SP 800-63B-4 for a password used as the only authentication factor; there are no composition rules. The upper bound limits the cost of password hashing. Generated client validators count UTF-16 code units, so a password with characters outside the Basic Multilingual Plane can pass the client check and fail on the server; a later client check should count code points. A password on the server blocklist of common or breached passwords answers 400 validation_failed with the pointer `/password`. The value is never returned, logged, or echoed in a problem. + LoginPassword: + type: string + minLength: 1 + maxLength: 128 + description: Password entered at login. The server applies the same NFKC normalization as at registration before it verifies the hash. Only the hashing bound applies, so a later change of the registration policy does not lock out existing accounts and a login error does not reveal the policy. The value is never returned, logged, or echoed in a problem. + AccountScenario: + type: string + description: 'Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, `employer` represents a company that searches for candidates. The scenario selects the onboarding steps.' + enum: + - candidate + - employer + OnboardingStep: + type: string + description: |- + Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly. + + - candidate_consents: candidate consents beyond C1, which was given at registration. + - candidate_profile: candidate profile. + - candidate_questionnaire: candidate questionnaire. + - candidate_assessment: choice of the expected grade and the assessment. + - employer_company: company profile of the employer. + - completed: onboarding is finished; the client opens the scenario home. + + Candidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change. + enum: + - candidate_consents + - candidate_profile + - candidate_questionnaire + - candidate_assessment + - employer_company + - completed + ConsentPurpose: + type: string + description: 'Consent whose text the client may read before an account exists. Only the consents given at registration are listed: `c1` is the consent to the processing of personal data.' + enum: + - c1 + ConsentText: + type: object + description: Currently published consent text. The server stores an acceptance with `text_version` and the hash of exactly this text. + additionalProperties: false + required: + - purpose + - text_version + - text + - published_at + properties: + purpose: + $ref: '#/components/schemas/ConsentPurpose' + text_version: + $ref: '#/components/schemas/ConsentTextVersion' + text: + type: string + minLength: 1 + maxLength: 100000 + description: Full consent text in plain UTF-8; paragraphs are separated by an empty line. The client shows it as text, never as HTML. + published_at: + $ref: '#/components/schemas/Timestamp' + ConsentTextVersion: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9._-]+$ + description: Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash. + examples: + - c1-2026-10-01 + PersonalDataConsentAcceptance: + type: object + description: Consent C1 to the processing of personal data, given at registration. The client reads the current text and its version with GetConsentText(c1) and sends that version here. A version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c1/text_version`; the client then reads the text again and asks the user to accept the new version. Unknown fields are rejected, so registration cannot carry any other consent; in particular, C4 is never part of registration. + additionalProperties: false + required: + - text_version + - accepted + properties: + text_version: + $ref: '#/components/schemas/ConsentTextVersion' + accepted: + type: boolean + enum: + - true + description: Explicit acceptance. Only true is valid. + RegistrationRequest: + type: object + description: New account with its scenario and consent C1. + additionalProperties: false + required: + - email + - password + - scenario + - consent_c1 + properties: + email: + $ref: '#/components/schemas/EmailAddress' + password: + $ref: '#/components/schemas/NewPassword' + scenario: + $ref: '#/components/schemas/AccountScenario' + consent_c1: + $ref: '#/components/schemas/PersonalDataConsentAcceptance' + EmailVerificationResendRequest: + type: object + description: Address that should receive a new verification link. + additionalProperties: false + required: + - email + properties: + email: + $ref: '#/components/schemas/EmailAddress' + IdentityRequestAccepted: + type: object + description: Neutral acknowledgement. Its content is identical whether or not the address belongs to an account or is already verified, so the response does not enumerate accounts. The client tells the user to check the mailbox. + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - accepted + VerificationToken: + type: string + minLength: 32 + maxLength: 128 + pattern: ^[A-Za-z0-9_-]+$ + description: 'One-time raw token copied from the verification link. It is request input only: the server stores only its hash and never returns a token.' + EmailVerificationRequest: + type: object + description: Token from the email verification link. + additionalProperties: false + required: + - token + properties: + token: + $ref: '#/components/schemas/VerificationToken' + EmailVerificationResult: + type: object + description: Result of a successful email verification. It does not start a session; the user signs in next and continues from `onboarding_step`. + additionalProperties: false + required: + - email_verified + - scenario + - onboarding_step + properties: + email_verified: + type: boolean + enum: + - true + description: Always true in a successful response. + scenario: + $ref: '#/components/schemas/AccountScenario' + onboarding_step: + $ref: '#/components/schemas/OnboardingStep' + LoginRequest: + type: object + description: Email and password of the account. + additionalProperties: false + required: + - email + - password + properties: + email: + $ref: '#/components/schemas/EmailAddress' + password: + $ref: '#/components/schemas/LoginPassword' + CsrfToken: + type: string + minLength: 32 + maxLength: 128 + pattern: ^[A-Za-z0-9_-]+$ + description: CSRF token bound to the current session. The client keeps it in memory only and sends it in the X-CSRF-Token header of every mutating request that requires a session. It changes when a new session starts. + Account: + type: object + description: Current account view. It never contains password hashes, token hashes, session identifiers, or other storage secrets. + additionalProperties: false + required: + - id + - email + - email_verified + - scenario + - onboarding_step + - created_at + properties: + id: + type: string + format: uuid + description: Account identifier. + email: + $ref: '#/components/schemas/EmailAddress' + email_verified: + type: boolean + description: Whether the address is verified. A session exists only for a verified account, so this is true in every current response. + scenario: + $ref: '#/components/schemas/AccountScenario' + onboarding_step: + $ref: '#/components/schemas/OnboardingStep' + created_at: + $ref: '#/components/schemas/Timestamp' + Session: + type: object + description: 'Current session as the client may see it: the account and the CSRF token. The session identifier itself travels only in the HttpOnly session cookie and never appears in a body.' + additionalProperties: false + required: + - account + - csrf_token + properties: + account: + $ref: '#/components/schemas/Account' + csrf_token: + $ref: '#/components/schemas/CsrfToken' HealthResponse: type: object additionalProperties: false @@ -257,6 +831,32 @@ components: minimum: 0 maximum: 86400 example: 30 + SessionCookieSet: + description: Sets the session cookie `__Host-lincodex_session` with an opaque random value and the attributes `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain. The `__Host-` prefix makes the browser reject the cookie without Secure and Path=/ or with a Domain. Max-Age equals the remaining absolute session lifetime. The value is never readable by scripts or present in a body. + required: true + schema: + type: string + minLength: 1 + maxLength: 4096 + pattern: ^__Host-lincodex_session= + example: __Host-lincodex_session=opaque-session-value; Path=/; Max-Age=604800; Secure; HttpOnly; SameSite=Strict + SessionCookieCleared: + description: Removes the session cookie with an empty value, `Max-Age=0`, and the same attributes it was set with. + required: true + schema: + type: string + minLength: 1 + maxLength: 4096 + pattern: ^__Host-lincodex_session= + example: __Host-lincodex_session=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=Strict + CacheControlNoStore: + description: '`no-store`: the response carries account or session data that browsers and intermediaries must not keep.' + required: true + schema: + type: string + enum: + - no-store + example: no-store responses: ValidationFailed: description: Parameters, headers, or the body do not match the contract, or the body violates a domain rule such as salary_from <= salary_to. The body has code validation_failed and lists the failing fields in `errors` with body or parameter pointers. @@ -395,6 +995,60 @@ components: $ref: '#/components/examples/Internal' not_implemented: $ref: '#/components/examples/NotImplemented' + RegistrationValidationFailed: + description: 'The body does not match the contract or violates a registration rule: a password outside 15-128 characters or on the blocklist, or a consent text version that is not the current one; code validation_failed with body pointers. An email that already belongs to an account is never a validation error.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + validation_failed: + $ref: '#/components/examples/RegistrationValidationFailed' + EmailVerificationFailed: + description: The token cannot verify an email. Code verification_token_expired means the token is past its lifetime; verification_token_invalid means it is unknown, already used, or replaced by a newer link; validation_failed with the pointer `/token` means the token is malformed. Nothing was changed in any case. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + verification_token_expired: + $ref: '#/components/examples/VerificationTokenExpired' + verification_token_invalid: + $ref: '#/components/examples/VerificationTokenInvalid' + validation_failed: + $ref: '#/components/examples/VerificationTokenMalformed' + InvalidCredentials: + description: The email and password do not match an account; code invalid_credentials. An unknown email and a wrong password get the same response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + invalid_credentials: + $ref: '#/components/examples/InvalidCredentials' + CsrfCheckFailed: + description: 'The request failed cross-site request protection: the X-CSRF-Token header is missing or does not belong to the session, or the Origin is not allowed; code csrf_check_failed. Nothing was changed.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + csrf_check_failed: + $ref: '#/components/examples/CsrfCheckFailed' + securitySchemes: + sessionCookie: + type: apiKey + in: cookie + name: __Host-lincodex_session + description: |- + Opaque random session identifier issued by Login in an HttpOnly cookie with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain. The server keeps the session in PostgreSQL, checks its expiry and revocation on every request, and derives the caller from it; operations never take a user identifier from the body. A session ends after an idle timeout of 24 hours or an absolute lifetime of 7 days, whichever comes first (planned values from configuration); activity extends only the idle deadline. A missing, unknown, expired, or revoked session answers 401 unauthenticated. Scripts cannot read the cookie, and it never appears in a body, log, or problem. + + SameSite=Strict costs the single-page application nothing: its HTML is public and every API call is a same-origin fetch, which carries the cookie even right after a cross-site navigation, while cross-site requests never carry it. + sessionCsrf: + type: apiKey + in: header + name: X-CSRF-Token + description: 'Synchronizer token bound to the session, returned by Login and GetCurrentSession. Every mutating operation that requires a session also requires this header; a missing token or one that does not belong to the session answers 403 csrf_check_failed. The token is defense in depth next to SameSite=Strict and the Origin check: every unsafe request (POST, PUT, PATCH, DELETE), including public ones such as Login, must carry an Origin from the configured allowlist, otherwise it answers 403 csrf_check_failed; a missing Origin is rejected too, and the server never derives the allowed Origin from the Host header. Request bodies are accepted only as application/json, which a cross-site form cannot send. A backend test requires every unsafe operation that requires sessionCookie to require this scheme as well.' examples: ValidationFailed: summary: Request parameters do not match the contract @@ -455,24 +1109,33 @@ components: pointer: /salary_from code: invalid message: The value does not match the contract. - Unauthenticated: - summary: No valid session + RegistrationValidationFailed: + summary: The password is too short and the consent text is outdated value: - type: urn:lincodex:problem:unauthenticated - title: Authentication required - status: 401 - code: unauthenticated - detail: Sign in and repeat the request. - trace_id: 4f2d1c3b-6a5e-4d7f-8b9a-0c1d2e3f4a5b - Forbidden: - summary: The caller may not access the object + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 9b0c1d2e-3f4a-4b5c-8d6e-7f8a9b0c1d2e + errors: + - in: body + pointer: /password + code: invalid + message: The value does not match the contract. + - in: body + pointer: /consent_c1/text_version + code: invalid + message: The value does not match the contract. + CsrfCheckFailed: + summary: Missing or wrong CSRF token, or a disallowed Origin value: - type: urn:lincodex:problem:forbidden - title: Access denied + type: urn:lincodex:problem:csrf_check_failed + title: Cross-site request check failed status: 403 - code: forbidden - detail: You do not have permission to perform this operation. - trace_id: 7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d + code: csrf_check_failed + detail: Read the current session to get a new CSRF token and repeat the request. + trace_id: 8a9b0c1d-2e3f-4a4b-9c5d-6e7f8a9b0c1d IdempotencyInProgress: summary: The first request with this key is still running value: @@ -482,6 +1145,112 @@ components: code: idempotency_in_progress detail: Retry after the original request completes. trace_id: 2d3e4f5a-6b7c-4d8e-9f0a-1b2c3d4e5f6a + IdempotencyKeyReused: + summary: The same Idempotency-Key was sent with a different body + value: + type: urn:lincodex:problem:idempotency_key_reused + title: Idempotency key reused with a different request + status: 422 + code: idempotency_key_reused + detail: Use a new Idempotency-Key for a different request. + trace_id: 4f5a6b7c-8d9e-4f0a-9b1c-3d4e5f6a7b8c + RateLimited: + summary: Too many requests + value: + type: urn:lincodex:problem:rate_limited + title: Too many requests + status: 429 + code: rate_limited + detail: Wait for the Retry-After interval and retry. + trace_id: 6b7c8d9e-0f1a-4b2c-9d3e-5f6a7b8c9d0e + VerificationTokenExpired: + summary: The verification token is past its lifetime + value: + type: urn:lincodex:problem:verification_token_expired + title: Verification link expired + status: 400 + code: verification_token_expired + detail: Request a new verification link. + trace_id: 4c5d6e7f-8a9b-4c0d-9e1f-2a3b4c5d6e7f + VerificationTokenInvalid: + summary: The verification token is unknown, used, or replaced + value: + type: urn:lincodex:problem:verification_token_invalid + title: Verification link is not valid + status: 400 + code: verification_token_invalid + detail: Request a new verification link, or sign in if the address is already verified. + trace_id: 3b4c5d6e-7f8a-4b9c-8d0e-1f2a3b4c5d6e + VerificationTokenMalformed: + summary: The token from the link is malformed + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 5d6e7f8a-9b0c-4d1e-8f2a-3b4c5d6e7f8a + errors: + - in: body + pointer: /token + code: invalid + message: The value does not match the contract. + CandidateSession: + summary: Session of a verified candidate + value: + account: + id: 0f8b6c2e-4d1a-4e7b-9c3f-5a2d8e6b1c47 + email: candidate@example.com + email_verified: true + scenario: candidate + onboarding_step: candidate_questionnaire + created_at: '2026-10-05T09:30:00Z' + csrf_token: Xk4pR9tV2mQ7wL1sN8bC5dF0gH3jZ6yA9eU2iO7rT4c + InvalidCredentials: + summary: Unknown email or wrong password + value: + type: urn:lincodex:problem:invalid_credentials + title: Invalid email or password + status: 401 + code: invalid_credentials + detail: Check the email and password and try again. + trace_id: 6e7f8a9b-0c1d-4e2f-9a3b-4c5d6e7f8a9b + EmailNotVerified: + summary: Correct credentials for an unverified email + value: + type: urn:lincodex:problem:email_not_verified + title: Email not verified + status: 403 + code: email_not_verified + detail: Confirm the email address with the link from the verification message. + trace_id: 7f8a9b0c-1d2e-4f3a-8b4c-5d6e7f8a9b0c + Unauthenticated: + summary: No valid session + value: + type: urn:lincodex:problem:unauthenticated + title: Authentication required + status: 401 + code: unauthenticated + detail: Sign in and repeat the request. + trace_id: 4f2d1c3b-6a5e-4d7f-8b9a-0c1d2e3f4a5b + CandidateAccount: + summary: A verified candidate on the questionnaire step + value: + id: 0f8b6c2e-4d1a-4e7b-9c3f-5a2d8e6b1c47 + email: candidate@example.com + email_verified: true + scenario: candidate + onboarding_step: candidate_questionnaire + created_at: '2026-10-05T09:30:00Z' + Forbidden: + summary: The caller may not access the object + value: + type: urn:lincodex:problem:forbidden + title: Access denied + status: 403 + code: forbidden + detail: You do not have permission to perform this operation. + trace_id: 7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d StateConflict: summary: The resource state does not allow the operation value: @@ -509,15 +1278,6 @@ components: code: payload_too_large detail: Reduce the request body size and retry. trace_id: 8b9c0d1e-2f3a-4b4c-9d5e-6f7a8b9c0d1e - IdempotencyKeyReused: - summary: The same Idempotency-Key was sent with a different body - value: - type: urn:lincodex:problem:idempotency_key_reused - title: Idempotency key reused with a different request - status: 422 - code: idempotency_key_reused - detail: Use a new Idempotency-Key for a different request. - trace_id: 4f5a6b7c-8d9e-4f0a-9b1c-3d4e5f6a7b8c PreconditionRequired: summary: The operation requires If-Match value: @@ -527,12 +1287,3 @@ components: code: precondition_required detail: Send If-Match with the ETag of the version you read. trace_id: 5a6b7c8d-9e0f-4a1b-8c2d-4e5f6a7b8c9d - RateLimited: - summary: Too many requests - value: - type: urn:lincodex:problem:rate_limited - title: Too many requests - status: 429 - code: rate_limited - detail: Wait for the Retry-After interval and retry. - trace_id: 6b7c8d9e-0f1a-4b2c-9d3e-5f6a7b8c9d0e diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 2c0d003..d85358c 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -4,9 +4,35 @@ info: version: 0.1.0 servers: - url: / +tags: + - name: health + description: Liveness of the API process. + - name: identity + description: >- + Registration, email verification, login, logout, and the current + account. Sessions are server-side and travel in an HttpOnly cookie; + mutating requests that require a session also carry a CSRF token. +# Operations require a session unless they declare `security: []`, so a new +# operation that omits security is protected by default. +security: + - sessionCookie: [] paths: /api/v1/healthz: $ref: ./routes/healthz.yml + /api/v1/identity/consent-texts/{purpose}: + $ref: ./routes/identity_consent_texts.yml + /api/v1/identity/registrations: + $ref: ./routes/identity_registrations.yml + /api/v1/identity/email-verification-requests: + $ref: ./routes/identity_email_verification_requests.yml + /api/v1/identity/email-verifications: + $ref: ./routes/identity_email_verifications.yml + /api/v1/identity/sessions: + $ref: ./routes/identity_sessions.yml + /api/v1/identity/sessions/current: + $ref: ./routes/identity_sessions_current.yml + /api/v1/identity/me: + $ref: ./routes/identity_me.yml components: schemas: Problem: @@ -21,6 +47,44 @@ components: $ref: ./components/schemas.yml#/Timestamp PageInfo: $ref: ./components/schemas.yml#/PageInfo + EmailAddress: + $ref: ./components/schemas.yml#/EmailAddress + NewPassword: + $ref: ./components/schemas.yml#/NewPassword + LoginPassword: + $ref: ./components/schemas.yml#/LoginPassword + AccountScenario: + $ref: ./components/schemas.yml#/AccountScenario + OnboardingStep: + $ref: ./components/schemas.yml#/OnboardingStep + ConsentPurpose: + $ref: ./components/schemas.yml#/ConsentPurpose + ConsentText: + $ref: ./components/schemas.yml#/ConsentText + ConsentTextVersion: + $ref: ./components/schemas.yml#/ConsentTextVersion + PersonalDataConsentAcceptance: + $ref: ./components/schemas.yml#/PersonalDataConsentAcceptance + RegistrationRequest: + $ref: ./components/schemas.yml#/RegistrationRequest + EmailVerificationResendRequest: + $ref: ./components/schemas.yml#/EmailVerificationResendRequest + IdentityRequestAccepted: + $ref: ./components/schemas.yml#/IdentityRequestAccepted + VerificationToken: + $ref: ./components/schemas.yml#/VerificationToken + EmailVerificationRequest: + $ref: ./components/schemas.yml#/EmailVerificationRequest + EmailVerificationResult: + $ref: ./components/schemas.yml#/EmailVerificationResult + LoginRequest: + $ref: ./components/schemas.yml#/LoginRequest + CsrfToken: + $ref: ./components/schemas.yml#/CsrfToken + Account: + $ref: ./components/schemas.yml#/Account + Session: + $ref: ./components/schemas.yml#/Session parameters: IdempotencyKey: $ref: ./components/parameters.yml#/IdempotencyKey @@ -35,6 +99,12 @@ components: $ref: ./components/headers.yml#/ETag RetryAfter: $ref: ./components/headers.yml#/RetryAfter + SessionCookieSet: + $ref: ./components/headers.yml#/SessionCookieSet + SessionCookieCleared: + $ref: ./components/headers.yml#/SessionCookieCleared + CacheControlNoStore: + $ref: ./components/headers.yml#/CacheControlNoStore responses: ValidationFailed: $ref: ./components/responses.yml#/ValidationFailed @@ -64,3 +134,26 @@ components: $ref: ./components/responses.yml#/NotImplemented Problem: $ref: ./components/responses.yml#/Problem + RegistrationValidationFailed: + $ref: ./components/responses.yml#/RegistrationValidationFailed + EmailVerificationFailed: + $ref: ./components/responses.yml#/EmailVerificationFailed + InvalidCredentials: + $ref: ./components/responses.yml#/InvalidCredentials + CsrfCheckFailed: + $ref: ./components/responses.yml#/CsrfCheckFailed + securitySchemes: + sessionCookie: + type: apiKey + in: cookie + name: __Host-lincodex_session + description: |- + Opaque random session identifier issued by Login in an HttpOnly cookie with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain. The server keeps the session in PostgreSQL, checks its expiry and revocation on every request, and derives the caller from it; operations never take a user identifier from the body. A session ends after an idle timeout of 24 hours or an absolute lifetime of 7 days, whichever comes first (planned values from configuration); activity extends only the idle deadline. A missing, unknown, expired, or revoked session answers 401 unauthenticated. Scripts cannot read the cookie, and it never appears in a body, log, or problem. + + SameSite=Strict costs the single-page application nothing: its HTML is public and every API call is a same-origin fetch, which carries the cookie even right after a cross-site navigation, while cross-site requests never carry it. + sessionCsrf: + type: apiKey + in: header + name: X-CSRF-Token + description: |- + Synchronizer token bound to the session, returned by Login and GetCurrentSession. Every mutating operation that requires a session also requires this header; a missing token or one that does not belong to the session answers 403 csrf_check_failed. The token is defense in depth next to SameSite=Strict and the Origin check: every unsafe request (POST, PUT, PATCH, DELETE), including public ones such as Login, must carry an Origin from the configured allowlist, otherwise it answers 403 csrf_check_failed; a missing Origin is rejected too, and the server never derives the allowed Origin from the Host header. Request bodies are accepted only as application/json, which a cross-site form cannot send. A backend test requires every unsafe operation that requires sessionCookie to require this scheme as well. diff --git a/api/core/routes/identity_consent_texts.yml b/api/core/routes/identity_consent_texts.yml new file mode 100644 index 0000000..d56c3f5 --- /dev/null +++ b/api/core/routes/identity_consent_texts.yml @@ -0,0 +1,37 @@ +get: + operationId: GetConsentText + summary: Read the currently published text of a registration consent. + description: |- + Public operation without a session. Returns the current text of a consent that is given before an account exists; only `c1` is available. The registration page shows this text and sends its `text_version` with RegisterAccount, and the server hashes the same stored text when it records the acceptance. If the text changes while the page is open, RegisterAccount answers 400 validation_failed with the pointer `/consent_c1/text_version`, and the page reads the text again. An unknown purpose fails parameter validation with 400. + security: [] + tags: + - identity + parameters: + - name: purpose + in: path + required: true + description: Consent whose text is requested. + schema: + $ref: ../components/schemas.yml#/ConsentPurpose + responses: + "200": + description: The current consent text. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsentText + examples: + c1: + summary: Current C1 text + value: + purpose: c1 + text_version: c1-2026-10-01 + text: |- + I consent to the processing of my personal data for registration and the use of the service. + + The full text is published by the operator. + published_at: "2026-10-01T00:00:00Z" + "400": + $ref: ../components/responses.yml#/ValidationFailed + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/identity_email_verification_requests.yml b/api/core/routes/identity_email_verification_requests.yml new file mode 100644 index 0000000..76a1d22 --- /dev/null +++ b/api/core/routes/identity_email_verification_requests.yml @@ -0,0 +1,43 @@ +post: + operationId: ResendEmailVerification + summary: Request a new email verification link. + description: |- + Public operation without a session. The answer is the same 202 for an unknown email, a verified email, and an unverified one, so it does not enumerate accounts. Only for an unverified account does the server issue a new one-time token bound to the current registration version, invalidate every earlier token of that account, and queue the message. Resend never changes the password, the scenario, or the consent record; a user who did not start the pending registration registers again instead, which replaces it. + + It is rate-limited per client and per email and answers 429 with Retry-After when the limit is reached. A retry is safe without Idempotency-Key: at worst it replaces the token again within the rate limit. Like every unsafe request, it requires an allowed Origin and answers 403 csrf_check_failed otherwise. + security: [] + tags: + - identity + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/EmailVerificationResendRequest + examples: + resend: + summary: Resend to an address + value: + email: candidate@example.com + responses: + "202": + description: >- + Request accepted. If the address belongs to an unverified account, a + new link is on its way; the response does not say whether it was. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/IdentityRequestAccepted + examples: + accepted: + summary: Neutral acknowledgement + value: + status: accepted + "400": + $ref: ../components/responses.yml#/ValidationFailed + "403": + $ref: ../components/responses.yml#/CsrfCheckFailed + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/identity_email_verifications.yml b/api/core/routes/identity_email_verifications.yml new file mode 100644 index 0000000..3979775 --- /dev/null +++ b/api/core/routes/identity_email_verifications.yml @@ -0,0 +1,47 @@ +post: + operationId: ConfirmEmail + summary: Verify an email with the one-time token from the link. + description: |- + Public operation without a session. The verification link has the form `/verify-email#token=`: the token travels in the URL fragment, so it never reaches a server log or a Referer header. The page first removes the fragment with `history.replaceState`, then waits for an explicit user action, such as a Confirm button, before it posts the token here. A link scanner that only fetches the page therefore does not consume the token. + + The server looks up the token by its hash and, in one transaction, checks that it is unused, not expired, and bound to the current registration version, marks it used, and marks the email verified. Only one of several parallel requests with the same token succeeds. An expired token answers verification_token_expired; an unknown, used, replaced, or superseded token answers verification_token_invalid; neither changes anything. For both, the client offers a new link and sign-in, because the address may already be verified. + + A repeated confirmation with an already used token is not an idempotent 200: exactly one request may succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after either outcome is sign-in anyway. + + Success does not start a session: the link may be opened on another device or by a mail scanner, and a session must come only from the password. The response returns the scenario and the saved onboarding step so the client can continue after sign-in. The operation is rate-limited and requires an allowed Origin. + security: [] + tags: + - identity + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/EmailVerificationRequest + examples: + token: + summary: Token from the link + value: + token: q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE + responses: + "200": + description: The email is verified. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/EmailVerificationResult + examples: + candidate: + summary: A candidate continues with consents + value: + email_verified: true + scenario: candidate + onboarding_step: candidate_consents + "400": + $ref: ../components/responses.yml#/EmailVerificationFailed + "403": + $ref: ../components/responses.yml#/CsrfCheckFailed + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/identity_me.yml b/api/core/routes/identity_me.yml new file mode 100644 index 0000000..fd812b9 --- /dev/null +++ b/api/core/routes/identity_me.yml @@ -0,0 +1,26 @@ +get: + operationId: GetCurrentAccount + summary: Read the account of the current session. + description: |- + Requires the session cookie. The account comes from the session, never from a request parameter. The client uses `scenario` and `onboarding_step` to return the user to the unfinished onboarding step. A missing, unknown, expired, or revoked session answers 401 unauthenticated. An unverified account never has a session, because login answers 403 email_not_verified for it, so this operation also answers 401 for such an account. + security: + - sessionCookie: [] + tags: + - identity + responses: + "200": + description: The current account. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/Account + examples: + candidate: + $ref: ../components/examples.yml#/CandidateAccount + "401": + $ref: ../components/responses.yml#/Unauthenticated + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/identity_registrations.yml b/api/core/routes/identity_registrations.yml new file mode 100644 index 0000000..32420be --- /dev/null +++ b/api/core/routes/identity_registrations.yml @@ -0,0 +1,67 @@ +post: + operationId: RegisterAccount + summary: Register an account by email with a scenario and consent C1. + description: |- + Public operation without a session. The client reads the current C1 text with GetConsentText and sends the email, the password, the chosen scenario, and consent C1 with the version of the text the user accepted. + + The answer is the same 202 whether the email is new, registered but not verified, or verified, so registration does not enumerate accounts: + + - New email: the server creates an unverified account with the scenario and the first onboarding step, records C1 with its text version and text hash, stores only the hash of a one-time verification token, and queues the verification message, all in one transaction. + - Registered but not verified: the server treats the request as a new registration of that address. In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1 record, advances the registration version, invalidates every earlier verification token, and queues a message with a new token. A pre-registration with someone else's password therefore never survives the address owner's own registration. + - Verified: nothing changes. The server may queue a rate-limited "you already have an account" notice to the address. + + Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration can never confirm the newer credentials. An account that stays unverified is deleted with its consent record and tokens 7 days after its last registration (planned value from configuration). Verification tokens live 24 hours (planned value from configuration). + + The response does not depend on the branch in content or timing. Before it looks up the email, the server validates the whole body, including the password bounds after normalization, the password blocklist, and the C1 version, and it computes the Argon2id hash on every branch; a 400 therefore never depends on whether the email exists. Mail is delivered asynchronously from the outbox. + + The operation requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email, and the request fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The server never stores the body, the password, or a plain hash of either; the secret keeps the fingerprint from serving as an offline password check. A retry with the same key, email, and body replays the stored 202 without a second message; the same key and email with a different body answers 422 idempotency_key_reused. + + It is rate-limited per client and per email and answers 429 with Retry-After when the limit is reached. Like every unsafe request, it requires an allowed Origin and answers 403 csrf_check_failed otherwise. + security: [] + tags: + - identity + parameters: + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RegistrationRequest + examples: + candidate: + summary: Candidate registration + value: + email: candidate@example.com + password: correct horse battery staple + scenario: candidate + consent_c1: + text_version: c1-2026-10-01 + accepted: true + responses: + "202": + description: >- + Registration request accepted. If the email can be registered, a + verification link is on its way; the response does not say whether + it was. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/IdentityRequestAccepted + examples: + accepted: + summary: Neutral acknowledgement + value: + status: accepted + "400": + $ref: ../components/responses.yml#/RegistrationValidationFailed + "403": + $ref: ../components/responses.yml#/CsrfCheckFailed + "409": + $ref: ../components/responses.yml#/IdempotencyInProgress + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/identity_sessions.yml b/api/core/routes/identity_sessions.yml new file mode 100644 index 0000000..6d96fae --- /dev/null +++ b/api/core/routes/identity_sessions.yml @@ -0,0 +1,62 @@ +post: + operationId: Login + summary: Sign in with email and password and start a session. + description: |- + Public operation that starts a server session. The server verifies the password with Argon2id; for an unknown email it verifies against a fixed dummy hash, so the response time does not reveal whether the account exists. An unknown email and a wrong password both answer 401 invalid_credentials. + + Correct credentials for an unverified email answer 403 email_not_verified and create no session. This reveals the verification state only to someone who already knows the password, which proves more than the state itself; the client offers to resend the link. + + On success the server revokes the session that the request carried, if any, creates a new random session in PostgreSQL with a new identifier and a new CSRF token, sets the HttpOnly session cookie, and returns the account and the CSRF token. The new session follows the idle and absolute timeouts of the sessionCookie scheme. The client keeps the token in memory and sends it in X-CSRF-Token with every mutating request that requires a session. + + Login is rate-limited per client and per email and answers 429 with Retry-After. Like every unsafe request, it requires an allowed Origin, which protects against login CSRF, and answers 403 csrf_check_failed otherwise. + security: [] + tags: + - identity + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LoginRequest + examples: + login: + summary: Email and password + value: + email: candidate@example.com + password: correct horse battery staple + responses: + "201": + description: Session started; the session cookie is set. + headers: + Set-Cookie: + $ref: ../components/headers.yml#/SessionCookieSet + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/Session + examples: + candidate: + $ref: ../components/examples.yml#/CandidateSession + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/InvalidCredentials + "403": + description: >- + Correct credentials for an unverified email (email_not_verified), or + a disallowed Origin (csrf_check_failed). No session was created. + content: + application/problem+json: + schema: + $ref: ../components/schemas.yml#/Problem + examples: + email_not_verified: + $ref: ../components/examples.yml#/EmailNotVerified + csrf_check_failed: + $ref: ../components/examples.yml#/CsrfCheckFailed + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/identity_sessions_current.yml b/api/core/routes/identity_sessions_current.yml new file mode 100644 index 0000000..414e3f7 --- /dev/null +++ b/api/core/routes/identity_sessions_current.yml @@ -0,0 +1,60 @@ +get: + operationId: GetCurrentSession + summary: Read the current session and its CSRF token. + description: |- + Requires the session cookie. Returns the account and the CSRF token of the current session, so the client can restore the token after a page reload or after 403 csrf_check_failed. A missing, unknown, expired, or revoked session answers 401 unauthenticated. Cross-origin pages cannot read the token, because the API sends no Access-Control-Allow-Origin header. + security: + - sessionCookie: [] + tags: + - identity + responses: + "200": + description: The current session. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/Session + examples: + candidate: + $ref: ../components/examples.yml#/CandidateSession + "401": + $ref: ../components/responses.yml#/Unauthenticated + default: + $ref: ../components/responses.yml#/Problem +delete: + operationId: Logout + summary: Sign out and revoke the current session. + description: |- + Requires the session cookie and the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The server revokes the session in PostgreSQL, so the cookie value stops working even if a copy remains, and clears the cookie. A missing, expired, or revoked session answers 401 unauthenticated and also clears the cookie, so a stale cookie does not stay in the browser; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed and keeps the session and the cookie. The client clears its private query cache after the response. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - identity + responses: + "204": + description: The session is revoked and the cookie is cleared. + headers: + Set-Cookie: + $ref: ../components/headers.yml#/SessionCookieCleared + "401": + description: >- + No valid session; code unauthenticated. The cookie is cleared as + well. + headers: + Set-Cookie: + $ref: ../components/headers.yml#/SessionCookieCleared + content: + application/problem+json: + schema: + $ref: ../components/schemas.yml#/Problem + examples: + unauthenticated: + $ref: ../components/examples.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailed + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/ml/components/schemas.yml b/api/ml/components/schemas.yml index 28759b6..1c4b52a 100644 --- a/api/ml/components/schemas.yml +++ b/api/ml/components/schemas.yml @@ -90,11 +90,19 @@ ProblemCode: - internal (500): unexpected server error. - - not_implemented (501): the operation is in the contract but not implemented yet.' + - not_implemented (501): the operation is in the contract but not implemented yet. + + + The enum keeps the public API codes so both contracts share one Problem shape. The identity codes verification_token_invalid, verification_token_expired, invalid_credentials, email_not_verified, and csrf_check_failed belong to the public API; the ML service never returns them.' enum: - validation_failed + - verification_token_invalid + - verification_token_expired - unauthenticated + - invalid_credentials - forbidden + - email_not_verified + - csrf_check_failed - not_found - method_not_allowed - idempotency_in_progress diff --git a/api/ml/components/schemas/problem_schemas.yml b/api/ml/components/schemas/problem_schemas.yml index 0147d38..60b4213 100644 --- a/api/ml/components/schemas/problem_schemas.yml +++ b/api/ml/components/schemas/problem_schemas.yml @@ -86,10 +86,17 @@ schemas: - rate_limited (429): too many requests; see Retry-After. - internal (500): unexpected server error. - not_implemented (501): the operation is in the contract but not implemented yet. + + The enum keeps the public API codes so both contracts share one Problem shape. The identity codes verification_token_invalid, verification_token_expired, invalid_credentials, email_not_verified, and csrf_check_failed belong to the public API; the ML service never returns them. enum: - validation_failed + - verification_token_invalid + - verification_token_expired - unauthenticated + - invalid_credentials - forbidden + - email_not_verified + - csrf_check_failed - not_found - method_not_allowed - idempotency_in_progress diff --git a/api/ml/openapi.bundle.yml b/api/ml/openapi.bundle.yml index 503c1eb..5888edd 100644 --- a/api/ml/openapi.bundle.yml +++ b/api/ml/openapi.bundle.yml @@ -94,10 +94,17 @@ components: - rate_limited (429): too many requests; see Retry-After. - internal (500): unexpected server error. - not_implemented (501): the operation is in the contract but not implemented yet. + + The enum keeps the public API codes so both contracts share one Problem shape. The identity codes verification_token_invalid, verification_token_expired, invalid_credentials, email_not_verified, and csrf_check_failed belong to the public API; the ML service never returns them. enum: - validation_failed + - verification_token_invalid + - verification_token_expired - unauthenticated + - invalid_credentials - forbidden + - email_not_verified + - csrf_check_failed - not_found - method_not_allowed - idempotency_in_progress diff --git a/api/testdata/openapi-3.2.0.yml b/api/testdata/openapi-3.2.0.yml index 8573da0..85caf32 100644 --- a/api/testdata/openapi-3.2.0.yml +++ b/api/testdata/openapi-3.2.0.yml @@ -229,43 +229,38 @@ components: $ref: "#/components/schemas/ProblemFieldError" ProblemCode: type: string - description: - "Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. - + description: |- + Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. - + - verification_token_invalid (400): the email verification token is unknown, already used, or replaced by a newer one; request a new link or sign in. + - verification_token_expired (400): the email verification token is past its lifetime; request a new link. - unauthenticated (401): no valid session or credentials. - + - invalid_credentials (401): the email and password do not match an account; an unknown email and a wrong password are not distinguished. - forbidden (403): the caller is authenticated but not allowed. - + - email_not_verified (403): the credentials are correct but the email is not verified yet. + - csrf_check_failed (403): the request failed cross-site request protection: a missing or wrong X-CSRF-Token or a disallowed Origin. - not_found (404): the route or object does not exist or is not visible. - - method_not_allowed (405): the route does not support the method. - - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. - - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. - - version_conflict (412): If-Match does not match the current version. - - payload_too_large (413): the request body exceeds the limit. - - unsupported_media_type (415): the request Content-Type is not accepted. - - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. - - precondition_required (428): the operation requires If-Match. - - rate_limited (429): too many requests; see Retry-After. - - internal (500): unexpected server error. - - - not_implemented (501): the operation is in the contract but not implemented yet." + - not_implemented (501): the operation is in the contract but not implemented yet. enum: - validation_failed + - verification_token_invalid + - verification_token_expired - unauthenticated + - invalid_credentials - forbidden + - email_not_verified + - csrf_check_failed - not_found - method_not_allowed - idempotency_in_progress diff --git a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go index 39d14c1..09424b7 100644 --- a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go @@ -17,9 +17,12 @@ import ( ) var regexMap = map[string]ogenregex.Regexp{ - "^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"), - "^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"), - "^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"), + "^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"), + "^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"), + "^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"), + "^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"), + "^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"), + "^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="), } var ( // Allocate option closure once. diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index dd06272..4195fd1 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -10,6 +10,7 @@ import ( "github.com/go-faster/errors" ht "github.com/ogen-go/ogen/http" "github.com/ogen-go/ogen/middleware" + "github.com/ogen-go/ogen/ogenerrors" "github.com/ogen-go/ogen/otelogen" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" @@ -32,6 +33,717 @@ func (c *codeRecorder) Unwrap() http.ResponseWriter { return c.ResponseWriter } +// handleConfirmEmailRequest handles ConfirmEmail operation. +// +// Public operation without a session. The verification link has the form +// `/verify-email#token=`: the token travels in the URL fragment, so it never +// reaches a server log or a Referer header. The page first removes the fragment with +// `history.replaceState`, then waits for an explicit user action, such as a Confirm button, before it +// posts the token here. A link scanner that only fetches the page therefore does not consume the +// token. +// +// The server looks up the token by its hash and, in one transaction, checks that it is unused, not +// expired, and bound to the current registration version, marks it used, and marks the email verified. +// Only one of several parallel requests with the same token succeeds. An expired token answers +// verification_token_expired; an unknown, used, replaced, or superseded token answers +// verification_token_invalid; neither changes anything. For both, the client offers a new link and +// sign-in, because the address may already be verified. +// +// A repeated confirmation with an already used token is not an idempotent 200: exactly one request may +// succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after +// either outcome is sign-in anyway. +// +// Success does not start a session: the link may be opened on another device or by a mail scanner, and +// a session must come only from the password. The response returns the scenario and the saved +// onboarding step so the client can continue after sign-in. The operation is rate-limited and requires +// an allowed Origin. +// +// POST /api/v1/identity/email-verifications +func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ConfirmEmail"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/identity/email-verifications"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ConfirmEmailOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: ConfirmEmailOperation, + ID: "ConfirmEmail", + } + ) + + var rawBody []byte + request, rawBody, close, err := s.decodeConfirmEmailRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response ConfirmEmailRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ConfirmEmailOperation, + OperationSummary: "Verify an email with the one-time token from the link.", + OperationID: "ConfirmEmail", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = *EmailVerificationRequest + Params = struct{} + Response = ConfirmEmailRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ConfirmEmail(ctx, request) + return response, err + }, + ) + } else { + response, err = s.h.ConfirmEmail(ctx, request) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeConfirmEmailResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleGetConsentTextRequest handles GetConsentText operation. +// +// Public operation without a session. Returns the current text of a consent that is given before an +// account exists; only `c1` is available. The registration page shows this text and sends its +// `text_version` with RegisterAccount, and the server hashes the same stored text when it records the +// acceptance. If the text changes while the page is open, RegisterAccount answers 400 +// validation_failed with the pointer `/consent_c1/text_version`, and the page reads the text again. An +// unknown purpose fails parameter validation with 400. +// +// GET /api/v1/identity/consent-texts/{purpose} +func (s *Server) handleGetConsentTextRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetConsentText"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/identity/consent-texts/{purpose}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetConsentTextOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetConsentTextOperation, + ID: "GetConsentText", + } + ) + params, err := decodeGetConsentTextParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response GetConsentTextRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetConsentTextOperation, + OperationSummary: "Read the currently published text of a registration consent.", + OperationID: "GetConsentText", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "purpose", + In: "path", + }: params.Purpose, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetConsentTextParams + Response = GetConsentTextRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetConsentTextParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetConsentText(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetConsentText(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetConsentTextResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleGetCurrentAccountRequest handles GetCurrentAccount operation. +// +// Requires the session cookie. The account comes from the session, never from a request parameter. The +// client uses `scenario` and `onboarding_step` to return the user to the unfinished onboarding step. A +// missing, unknown, expired, or revoked session answers 401 unauthenticated. An unverified account +// never has a session, because login answers 403 email_not_verified for it, so this operation also +// answers 401 for such an account. +// +// GET /api/v1/identity/me +func (s *Server) handleGetCurrentAccountRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetCurrentAccount"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/identity/me"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetCurrentAccountOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetCurrentAccountOperation, + ID: "GetCurrentAccount", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetCurrentAccountOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + + var response GetCurrentAccountRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetCurrentAccountOperation, + OperationSummary: "Read the account of the current session.", + OperationID: "GetCurrentAccount", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = GetCurrentAccountRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetCurrentAccount(ctx) + return response, err + }, + ) + } else { + response, err = s.h.GetCurrentAccount(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetCurrentAccountResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleGetCurrentSessionRequest handles GetCurrentSession operation. +// +// Requires the session cookie. Returns the account and the CSRF token of the current session, so the +// client can restore the token after a page reload or after 403 csrf_check_failed. A missing, unknown, +// expired, or revoked session answers 401 unauthenticated. Cross-origin pages cannot read the token, +// because the API sends no Access-Control-Allow-Origin header. +// +// GET /api/v1/identity/sessions/current +func (s *Server) handleGetCurrentSessionRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetCurrentSession"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/identity/sessions/current"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetCurrentSessionOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetCurrentSessionOperation, + ID: "GetCurrentSession", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetCurrentSessionOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + + var response GetCurrentSessionRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetCurrentSessionOperation, + OperationSummary: "Read the current session and its CSRF token.", + OperationID: "GetCurrentSession", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = GetCurrentSessionRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetCurrentSession(ctx) + return response, err + }, + ) + } else { + response, err = s.h.GetCurrentSession(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetCurrentSessionResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleGetHealthzRequest handles GetHealthz operation. // // Check whether the API process is responding. @@ -166,3 +878,752 @@ func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w htt return } } + +// handleLoginRequest handles Login operation. +// +// Public operation that starts a server session. The server verifies the password with Argon2id; for +// an unknown email it verifies against a fixed dummy hash, so the response time does not reveal +// whether the account exists. An unknown email and a wrong password both answer 401 +// invalid_credentials. +// +// Correct credentials for an unverified email answer 403 email_not_verified and create no session. +// This reveals the verification state only to someone who already knows the password, which proves +// more than the state itself; the client offers to resend the link. +// +// On success the server revokes the session that the request carried, if any, creates a new random +// session in PostgreSQL with a new identifier and a new CSRF token, sets the HttpOnly session cookie, +// and returns the account and the CSRF token. The new session follows the idle and absolute timeouts +// of the sessionCookie scheme. The client keeps the token in memory and sends it in X-CSRF-Token with +// every mutating request that requires a session. +// +// Login is rate-limited per client and per email and answers 429 with Retry-After. Like every unsafe +// request, it requires an allowed Origin, which protects against login CSRF, and answers 403 +// csrf_check_failed otherwise. +// +// POST /api/v1/identity/sessions +func (s *Server) handleLoginRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("Login"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/identity/sessions"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), LoginOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: LoginOperation, + ID: "Login", + } + ) + + var rawBody []byte + request, rawBody, close, err := s.decodeLoginRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response LoginRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: LoginOperation, + OperationSummary: "Sign in with email and password and start a session.", + OperationID: "Login", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = *LoginRequest + Params = struct{} + Response = LoginRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.Login(ctx, request) + return response, err + }, + ) + } else { + response, err = s.h.Login(ctx, request) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeLoginResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleLogoutRequest handles Logout operation. +// +// Requires the session cookie and the CSRF token of that session in X-CSRF-Token, and an allowed +// Origin. The server revokes the session in PostgreSQL, so the cookie value stops working even if a +// copy remains, and clears the cookie. A missing, expired, or revoked session answers 401 +// unauthenticated and also clears the cookie, so a stale cookie does not stay in the browser; a +// missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed and keeps the +// session and the cookie. The client clears its private query cache after the response. +// +// DELETE /api/v1/identity/sessions/current +func (s *Server) handleLogoutRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("Logout"), + semconv.HTTPRequestMethodKey.String("DELETE"), + semconv.HTTPRouteKey.String("/api/v1/identity/sessions/current"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), LogoutOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: LogoutOperation, + ID: "Logout", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, LogoutOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, LogoutOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + + var response LogoutRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: LogoutOperation, + OperationSummary: "Sign out and revoke the current session.", + OperationID: "Logout", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = LogoutRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.Logout(ctx) + return response, err + }, + ) + } else { + response, err = s.h.Logout(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeLogoutResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleRegisterAccountRequest handles RegisterAccount operation. +// +// Public operation without a session. The client reads the current C1 text with GetConsentText and +// sends the email, the password, the chosen scenario, and consent C1 with the version of the text the +// user accepted. +// +// The answer is the same 202 whether the email is new, registered but not verified, or verified, so +// registration does not enumerate accounts: +// +// - New email: the server creates an unverified account with the scenario and the first onboarding +// step, records C1 with its text version and text hash, stores only the hash of a one-time +// verification token, and queues the verification message, all in one transaction. +// - Registered but not verified: the server treats the request as a new registration of that address. +// In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1 +// record, advances the registration version, invalidates every earlier verification token, and +// queues a message with a new token. A pre-registration with someone else's password therefore +// never survives the address owner's own registration. +// - Verified: nothing changes. The server may queue a rate-limited "you already have an account" +// notice to the address. +// +// Every verification token is bound to the registration version it was issued for, so a token issued +// before a re-registration can never confirm the newer credentials. An account that stays unverified +// is deleted with its consent record and tokens 7 days after its last registration (planned value from +// configuration). Verification tokens live 24 hours (planned value from configuration). +// +// The response does not depend on the branch in content or timing. Before it looks up the email, the +// server validates the whole body, including the password bounds after normalization, the password +// blocklist, and the C1 version, and it computes the Argon2id hash on every branch; a 400 therefore +// never depends on whether the email exists. Mail is delivered asynchronously from the outbox. +// +// The operation requires Idempotency-Key. For this anonymous operation the key is scoped by the +// operation, the key, and an HMAC of the normalized email, and the request fingerprint is an +// HMAC-SHA-256 with a server secret over the canonical JSON body. The server never stores the body, +// the password, or a plain hash of either; the secret keeps the fingerprint from serving as an offline +// password check. A retry with the same key, email, and body replays the stored 202 without a second +// message; the same key and email with a different body answers 422 idempotency_key_reused. +// +// It is rate-limited per client and per email and answers 429 with Retry-After when the limit is +// reached. Like every unsafe request, it requires an allowed Origin and answers 403 csrf_check_failed +// otherwise. +// +// POST /api/v1/identity/registrations +func (s *Server) handleRegisterAccountRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("RegisterAccount"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/identity/registrations"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), RegisterAccountOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: RegisterAccountOperation, + ID: "RegisterAccount", + } + ) + params, err := decodeRegisterAccountParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeRegisterAccountRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response RegisterAccountRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: RegisterAccountOperation, + OperationSummary: "Register an account by email with a scenario and consent C1.", + OperationID: "RegisterAccount", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *RegistrationRequest + Params = RegisterAccountParams + Response = RegisterAccountRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackRegisterAccountParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.RegisterAccount(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.RegisterAccount(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeRegisterAccountResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleResendEmailVerificationRequest handles ResendEmailVerification operation. +// +// Public operation without a session. The answer is the same 202 for an unknown email, a verified +// email, and an unverified one, so it does not enumerate accounts. Only for an unverified account does +// the server issue a new one-time token bound to the current registration version, invalidate every +// earlier token of that account, and queue the message. Resend never changes the password, the +// scenario, or the consent record; a user who did not start the pending registration registers again +// instead, which replaces it. +// +// It is rate-limited per client and per email and answers 429 with Retry-After when the limit is +// reached. A retry is safe without Idempotency-Key: at worst it replaces the token again within the +// rate limit. Like every unsafe request, it requires an allowed Origin and answers 403 +// csrf_check_failed otherwise. +// +// POST /api/v1/identity/email-verification-requests +func (s *Server) handleResendEmailVerificationRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ResendEmailVerification"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/identity/email-verification-requests"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ResendEmailVerificationOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: ResendEmailVerificationOperation, + ID: "ResendEmailVerification", + } + ) + + var rawBody []byte + request, rawBody, close, err := s.decodeResendEmailVerificationRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response ResendEmailVerificationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ResendEmailVerificationOperation, + OperationSummary: "Request a new email verification link.", + OperationID: "ResendEmailVerification", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = *EmailVerificationResendRequest + Params = struct{} + Response = ResendEmailVerificationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ResendEmailVerification(ctx, request) + return response, err + }, + ) + } else { + response, err = s.h.ResendEmailVerification(ctx, request) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeResendEmailVerificationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go new file mode 100644 index 0000000..234c2bf --- /dev/null +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -0,0 +1,34 @@ +// Code generated by ogen, DO NOT EDIT. +package api + +type ConfirmEmailRes interface { + confirmEmailRes() +} + +type GetConsentTextRes interface { + getConsentTextRes() +} + +type GetCurrentAccountRes interface { + getCurrentAccountRes() +} + +type GetCurrentSessionRes interface { + getCurrentSessionRes() +} + +type LoginRes interface { + loginRes() +} + +type LogoutRes interface { + logoutRes() +} + +type RegisterAccountRes interface { + registerAccountRes() +} + +type ResendEmailVerificationRes interface { + resendEmailVerificationRes() +} diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index 7688eca..2d7c332 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -5,12 +5,946 @@ package api import ( "math/bits" "strconv" + "time" "github.com/go-faster/errors" "github.com/go-faster/jx" + "github.com/ogen-go/ogen/json" "github.com/ogen-go/ogen/validate" ) +// Encode implements json.Marshaler. +func (s *Account) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Account) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("email") + s.Email.Encode(e) + } + { + e.FieldStart("email_verified") + e.Bool(s.EmailVerified) + } + { + e.FieldStart("scenario") + s.Scenario.Encode(e) + } + { + e.FieldStart("onboarding_step") + s.OnboardingStep.Encode(e) + } + { + e.FieldStart("created_at") + s.CreatedAt.Encode(e) + } +} + +var jsonFieldsNameOfAccount = [6]string{ + 0: "id", + 1: "email", + 2: "email_verified", + 3: "scenario", + 4: "onboarding_step", + 5: "created_at", +} + +// Decode decodes Account from json. +func (s *Account) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Account to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "email": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Email.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"email\"") + } + case "email_verified": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Bool() + s.EmailVerified = bool(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"email_verified\"") + } + case "scenario": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Scenario.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"scenario\"") + } + case "onboarding_step": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.OnboardingStep.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"onboarding_step\"") + } + case "created_at": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.CreatedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"created_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Account") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAccount) { + name = jsonFieldsNameOfAccount[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *Account) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Account) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AccountScenario as json. +func (s AccountScenario) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AccountScenario from json. +func (s *AccountScenario) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AccountScenario to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AccountScenario(v) { + case AccountScenarioCandidate: + *s = AccountScenarioCandidate + case AccountScenarioEmployer: + *s = AccountScenarioEmployer + default: + *s = AccountScenario(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AccountScenario) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AccountScenario) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConfirmEmailBadRequest as json. +func (s *ConfirmEmailBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ConfirmEmailBadRequest from json. +func (s *ConfirmEmailBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConfirmEmailBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ConfirmEmailBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ConfirmEmailBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConfirmEmailBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConfirmEmailForbidden as json. +func (s *ConfirmEmailForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ConfirmEmailForbidden from json. +func (s *ConfirmEmailForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConfirmEmailForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ConfirmEmailForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ConfirmEmailForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConfirmEmailForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConsentPurpose as json. +func (s ConsentPurpose) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ConsentPurpose from json. +func (s *ConsentPurpose) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentPurpose to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ConsentPurpose(v) { + case ConsentPurposeC1: + *s = ConsentPurposeC1 + default: + *s = ConsentPurpose(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ConsentPurpose) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentPurpose) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ConsentText) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ConsentText) encodeFields(e *jx.Encoder) { + { + e.FieldStart("purpose") + s.Purpose.Encode(e) + } + { + e.FieldStart("text_version") + s.TextVersion.Encode(e) + } + { + e.FieldStart("text") + e.Str(s.Text) + } + { + e.FieldStart("published_at") + s.PublishedAt.Encode(e) + } +} + +var jsonFieldsNameOfConsentText = [4]string{ + 0: "purpose", + 1: "text_version", + 2: "text", + 3: "published_at", +} + +// Decode decodes ConsentText from json. +func (s *ConsentText) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentText to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "purpose": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Purpose.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"purpose\"") + } + case "text_version": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.TextVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"text_version\"") + } + case "text": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.Text = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"text\"") + } + case "published_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.PublishedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"published_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ConsentText") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfConsentText) { + name = jsonFieldsNameOfConsentText[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ConsentText) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentText) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConsentTextVersion as json. +func (s ConsentTextVersion) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes ConsentTextVersion from json. +func (s *ConsentTextVersion) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConsentTextVersion to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ConsentTextVersion(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ConsentTextVersion) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConsentTextVersion) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CsrfToken as json. +func (s CsrfToken) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes CsrfToken from json. +func (s *CsrfToken) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CsrfToken to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CsrfToken(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CsrfToken) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CsrfToken) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes EmailAddress as json. +func (s EmailAddress) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes EmailAddress from json. +func (s *EmailAddress) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode EmailAddress to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = EmailAddress(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s EmailAddress) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *EmailAddress) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *EmailVerificationRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *EmailVerificationRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("token") + s.Token.Encode(e) + } +} + +var jsonFieldsNameOfEmailVerificationRequest = [1]string{ + 0: "token", +} + +// Decode decodes EmailVerificationRequest from json. +func (s *EmailVerificationRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode EmailVerificationRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "token": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Token.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"token\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode EmailVerificationRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfEmailVerificationRequest) { + name = jsonFieldsNameOfEmailVerificationRequest[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *EmailVerificationRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *EmailVerificationRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *EmailVerificationResendRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *EmailVerificationResendRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("email") + s.Email.Encode(e) + } +} + +var jsonFieldsNameOfEmailVerificationResendRequest = [1]string{ + 0: "email", +} + +// Decode decodes EmailVerificationResendRequest from json. +func (s *EmailVerificationResendRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode EmailVerificationResendRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "email": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Email.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"email\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode EmailVerificationResendRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfEmailVerificationResendRequest) { + name = jsonFieldsNameOfEmailVerificationResendRequest[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *EmailVerificationResendRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *EmailVerificationResendRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *EmailVerificationResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *EmailVerificationResult) encodeFields(e *jx.Encoder) { + { + e.FieldStart("email_verified") + s.EmailVerified.Encode(e) + } + { + e.FieldStart("scenario") + s.Scenario.Encode(e) + } + { + e.FieldStart("onboarding_step") + s.OnboardingStep.Encode(e) + } +} + +var jsonFieldsNameOfEmailVerificationResult = [3]string{ + 0: "email_verified", + 1: "scenario", + 2: "onboarding_step", +} + +// Decode decodes EmailVerificationResult from json. +func (s *EmailVerificationResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode EmailVerificationResult to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "email_verified": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.EmailVerified.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"email_verified\"") + } + case "scenario": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Scenario.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"scenario\"") + } + case "onboarding_step": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.OnboardingStep.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"onboarding_step\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode EmailVerificationResult") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfEmailVerificationResult) { + name = jsonFieldsNameOfEmailVerificationResult[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *EmailVerificationResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *EmailVerificationResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes EmailVerificationResultEmailVerified as json. +func (s EmailVerificationResultEmailVerified) Encode(e *jx.Encoder) { + e.Bool(bool(s)) +} + +// Decode decodes EmailVerificationResultEmailVerified from json. +func (s *EmailVerificationResultEmailVerified) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode EmailVerificationResultEmailVerified to nil") + } + v, err := d.Bool() + if err != nil { + return err + } + *s = EmailVerificationResultEmailVerified(v) + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s EmailVerificationResultEmailVerified) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *EmailVerificationResultEmailVerified) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *HealthResponse) Encode(e *jx.Encoder) { e.ObjStart() @@ -143,6 +1077,489 @@ func (s *HealthResponseStatus) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *IdentityRequestAccepted) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *IdentityRequestAccepted) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfIdentityRequestAccepted = [1]string{ + 0: "status", +} + +// Decode decodes IdentityRequestAccepted from json. +func (s *IdentityRequestAccepted) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode IdentityRequestAccepted to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode IdentityRequestAccepted") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfIdentityRequestAccepted) { + name = jsonFieldsNameOfIdentityRequestAccepted[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *IdentityRequestAccepted) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *IdentityRequestAccepted) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes IdentityRequestAcceptedStatus as json. +func (s IdentityRequestAcceptedStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes IdentityRequestAcceptedStatus from json. +func (s *IdentityRequestAcceptedStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode IdentityRequestAcceptedStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch IdentityRequestAcceptedStatus(v) { + case IdentityRequestAcceptedStatusAccepted: + *s = IdentityRequestAcceptedStatusAccepted + default: + *s = IdentityRequestAcceptedStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s IdentityRequestAcceptedStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *IdentityRequestAcceptedStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes LoginBadRequest as json. +func (s *LoginBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes LoginBadRequest from json. +func (s *LoginBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LoginBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = LoginBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *LoginBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LoginBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes LoginForbidden as json. +func (s *LoginForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes LoginForbidden from json. +func (s *LoginForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LoginForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = LoginForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *LoginForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LoginForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes LoginPassword as json. +func (s LoginPassword) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes LoginPassword from json. +func (s *LoginPassword) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LoginPassword to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = LoginPassword(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s LoginPassword) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LoginPassword) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *LoginRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *LoginRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("email") + s.Email.Encode(e) + } + { + e.FieldStart("password") + s.Password.Encode(e) + } +} + +var jsonFieldsNameOfLoginRequest = [2]string{ + 0: "email", + 1: "password", +} + +// Decode decodes LoginRequest from json. +func (s *LoginRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LoginRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "email": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Email.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"email\"") + } + case "password": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Password.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"password\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode LoginRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfLoginRequest) { + name = jsonFieldsNameOfLoginRequest[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *LoginRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LoginRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes LoginUnauthorized as json. +func (s *LoginUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes LoginUnauthorized from json. +func (s *LoginUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode LoginUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = LoginUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *LoginUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *LoginUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes NewPassword as json. +func (s NewPassword) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes NewPassword from json. +func (s *NewPassword) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode NewPassword to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = NewPassword(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NewPassword) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NewPassword) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes OnboardingStep as json. +func (s OnboardingStep) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes OnboardingStep from json. +func (s *OnboardingStep) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode OnboardingStep to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch OnboardingStep(v) { + case OnboardingStepCandidateConsents: + *s = OnboardingStepCandidateConsents + case OnboardingStepCandidateProfile: + *s = OnboardingStepCandidateProfile + case OnboardingStepCandidateQuestionnaire: + *s = OnboardingStepCandidateQuestionnaire + case OnboardingStepCandidateAssessment: + *s = OnboardingStepCandidateAssessment + case OnboardingStepEmployerCompany: + *s = OnboardingStepEmployerCompany + case OnboardingStepCompleted: + *s = OnboardingStepCompleted + default: + *s = OnboardingStep(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OnboardingStep) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OnboardingStep) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes string as json. func (o OptString) Encode(e *jx.Encoder) { if !o.Set { @@ -178,6 +1595,147 @@ func (s *OptString) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *PersonalDataConsentAcceptance) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PersonalDataConsentAcceptance) encodeFields(e *jx.Encoder) { + { + e.FieldStart("text_version") + s.TextVersion.Encode(e) + } + { + e.FieldStart("accepted") + s.Accepted.Encode(e) + } +} + +var jsonFieldsNameOfPersonalDataConsentAcceptance = [2]string{ + 0: "text_version", + 1: "accepted", +} + +// Decode decodes PersonalDataConsentAcceptance from json. +func (s *PersonalDataConsentAcceptance) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PersonalDataConsentAcceptance to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "text_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.TextVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"text_version\"") + } + case "accepted": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Accepted.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"accepted\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PersonalDataConsentAcceptance") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPersonalDataConsentAcceptance) { + name = jsonFieldsNameOfPersonalDataConsentAcceptance[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *PersonalDataConsentAcceptance) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PersonalDataConsentAcceptance) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PersonalDataConsentAcceptanceAccepted as json. +func (s PersonalDataConsentAcceptanceAccepted) Encode(e *jx.Encoder) { + e.Bool(bool(s)) +} + +// Decode decodes PersonalDataConsentAcceptanceAccepted from json. +func (s *PersonalDataConsentAcceptanceAccepted) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PersonalDataConsentAcceptanceAccepted to nil") + } + v, err := d.Bool() + if err != nil { + return err + } + *s = PersonalDataConsentAcceptanceAccepted(v) + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PersonalDataConsentAcceptanceAccepted) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PersonalDataConsentAcceptanceAccepted) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *Problem) Encode(e *jx.Encoder) { e.ObjStart() @@ -420,10 +1978,20 @@ func (s *ProblemCode) Decode(d *jx.Decoder) error { switch ProblemCode(v) { case ProblemCodeValidationFailed: *s = ProblemCodeValidationFailed + case ProblemCodeVerificationTokenInvalid: + *s = ProblemCodeVerificationTokenInvalid + case ProblemCodeVerificationTokenExpired: + *s = ProblemCodeVerificationTokenExpired case ProblemCodeUnauthenticated: *s = ProblemCodeUnauthenticated + case ProblemCodeInvalidCredentials: + *s = ProblemCodeInvalidCredentials case ProblemCodeForbidden: *s = ProblemCodeForbidden + case ProblemCodeEmailNotVerified: + *s = ProblemCodeEmailNotVerified + case ProblemCodeCsrfCheckFailed: + *s = ProblemCodeCsrfCheckFailed case ProblemCodeNotFound: *s = ProblemCodeNotFound case ProblemCodeMethodNotAllowed: @@ -658,3 +2226,559 @@ func (s *ProblemFieldLocation) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } + +// Encode encodes RegisterAccountBadRequest as json. +func (s *RegisterAccountBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RegisterAccountBadRequest from json. +func (s *RegisterAccountBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RegisterAccountBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RegisterAccountBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RegisterAccountBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RegisterAccountBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RegisterAccountConflict as json. +func (s *RegisterAccountConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RegisterAccountConflict from json. +func (s *RegisterAccountConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RegisterAccountConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RegisterAccountConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RegisterAccountConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RegisterAccountConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RegisterAccountForbidden as json. +func (s *RegisterAccountForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RegisterAccountForbidden from json. +func (s *RegisterAccountForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RegisterAccountForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RegisterAccountForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RegisterAccountForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RegisterAccountForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RegisterAccountUnprocessableEntity as json. +func (s *RegisterAccountUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RegisterAccountUnprocessableEntity from json. +func (s *RegisterAccountUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RegisterAccountUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RegisterAccountUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RegisterAccountUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RegisterAccountUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *RegistrationRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *RegistrationRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("email") + s.Email.Encode(e) + } + { + e.FieldStart("password") + s.Password.Encode(e) + } + { + e.FieldStart("scenario") + s.Scenario.Encode(e) + } + { + e.FieldStart("consent_c1") + s.ConsentC1.Encode(e) + } +} + +var jsonFieldsNameOfRegistrationRequest = [4]string{ + 0: "email", + 1: "password", + 2: "scenario", + 3: "consent_c1", +} + +// Decode decodes RegistrationRequest from json. +func (s *RegistrationRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RegistrationRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "email": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Email.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"email\"") + } + case "password": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Password.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"password\"") + } + case "scenario": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Scenario.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"scenario\"") + } + case "consent_c1": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.ConsentC1.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"consent_c1\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode RegistrationRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfRegistrationRequest) { + name = jsonFieldsNameOfRegistrationRequest[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RegistrationRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RegistrationRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ResendEmailVerificationBadRequest as json. +func (s *ResendEmailVerificationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ResendEmailVerificationBadRequest from json. +func (s *ResendEmailVerificationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ResendEmailVerificationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ResendEmailVerificationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ResendEmailVerificationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ResendEmailVerificationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ResendEmailVerificationForbidden as json. +func (s *ResendEmailVerificationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ResendEmailVerificationForbidden from json. +func (s *ResendEmailVerificationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ResendEmailVerificationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ResendEmailVerificationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ResendEmailVerificationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ResendEmailVerificationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *Session) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Session) encodeFields(e *jx.Encoder) { + { + e.FieldStart("account") + s.Account.Encode(e) + } + { + e.FieldStart("csrf_token") + s.CsrfToken.Encode(e) + } +} + +var jsonFieldsNameOfSession = [2]string{ + 0: "account", + 1: "csrf_token", +} + +// Decode decodes Session from json. +func (s *Session) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Session to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "account": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Account.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"account\"") + } + case "csrf_token": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.CsrfToken.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"csrf_token\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Session") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfSession) { + name = jsonFieldsNameOfSession[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *Session) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Session) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes Timestamp as json. +func (s Timestamp) Encode(e *jx.Encoder) { + unwrapped := time.Time(s) + + json.EncodeDateTime(e, unwrapped) +} + +// Decode decodes Timestamp from json. +func (s *Timestamp) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Timestamp to nil") + } + var unwrapped time.Time + if err := func() error { + v, err := json.DecodeDateTime(d) + unwrapped = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = Timestamp(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s Timestamp) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Timestamp) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes VerificationToken as json. +func (s VerificationToken) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes VerificationToken from json. +func (s *VerificationToken) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode VerificationToken to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = VerificationToken(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s VerificationToken) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *VerificationToken) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index f9b5e3d..38cba76 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -6,5 +6,13 @@ package api type OperationName = string const ( - GetHealthzOperation OperationName = "GetHealthz" + ConfirmEmailOperation OperationName = "ConfirmEmail" + GetConsentTextOperation OperationName = "GetConsentText" + GetCurrentAccountOperation OperationName = "GetCurrentAccount" + GetCurrentSessionOperation OperationName = "GetCurrentSession" + GetHealthzOperation OperationName = "GetHealthz" + LoginOperation OperationName = "Login" + LogoutOperation OperationName = "Logout" + RegisterAccountOperation OperationName = "RegisterAccount" + ResendEmailVerificationOperation OperationName = "ResendEmailVerification" ) diff --git a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go new file mode 100644 index 0000000..e493d22 --- /dev/null +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -0,0 +1,183 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "net/http" + "net/url" + + "github.com/go-faster/errors" + "github.com/ogen-go/ogen/conv" + "github.com/ogen-go/ogen/middleware" + "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/uri" + "github.com/ogen-go/ogen/validate" +) + +// GetConsentTextParams is parameters of GetConsentText operation. +type GetConsentTextParams struct { + // Consent whose text is requested. + Purpose ConsentPurpose +} + +func unpackGetConsentTextParams(packed middleware.Parameters) (params GetConsentTextParams) { + { + key := middleware.ParameterKey{ + Name: "purpose", + In: "path", + } + params.Purpose = packed[key].(ConsentPurpose) + } + return params +} + +func decodeGetConsentTextParams(args [1]string, argsEscaped bool, r *http.Request) (params GetConsentTextParams, _ error) { + // Decode path: purpose. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "purpose", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.Purpose = ConsentPurpose(c) + return nil + }(); err != nil { + return err + } + if err := func() error { + if err := params.Purpose.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "purpose", + In: "path", + Err: err, + } + } + return params, nil +} + +// RegisterAccountParams is parameters of RegisterAccount operation. +type RegisterAccountParams struct { + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackRegisterAccountParams(packed middleware.Parameters) (params RegisterAccountParams) { + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeRegisterAccountParams(args [0]string, argsEscaped bool, r *http.Request) (params RegisterAccountParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} diff --git a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go index ae379a2..a96a608 100644 --- a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go @@ -1,3 +1,331 @@ // Code generated by ogen, DO NOT EDIT. package api + +import ( + "bytes" + "io" + "mime" + "net/http" + + "github.com/go-faster/errors" + "github.com/go-faster/jx" + "github.com/ogen-go/ogen/ogenerrors" + "github.com/ogen-go/ogen/validate" +) + +func (s *Server) decodeConfirmEmailRequest(r *http.Request) ( + req *EmailVerificationRequest, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request EmailVerificationRequest + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + +func (s *Server) decodeLoginRequest(r *http.Request) ( + req *LoginRequest, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request LoginRequest + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + +func (s *Server) decodeRegisterAccountRequest(r *http.Request) ( + req *RegistrationRequest, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request RegistrationRequest + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + +func (s *Server) decodeResendEmailVerificationRequest(r *http.Request) ( + req *EmailVerificationResendRequest, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request EmailVerificationResendRequest + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index aeaf05b..1029d7f 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -7,11 +7,213 @@ import ( "github.com/go-faster/errors" "github.com/go-faster/jx" + "github.com/ogen-go/ogen/conv" ht "github.com/ogen-go/ogen/http" + "github.com/ogen-go/ogen/uri" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" ) +func encodeConfirmEmailResponse(response ConfirmEmailRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *EmailVerificationResult: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ConfirmEmailBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ConfirmEmailForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeGetConsentTextResponse(response GetConsentTextRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *ConsentText: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *Problem: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeGetCurrentAccountResponse(response GetCurrentAccountRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AccountHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *Problem: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeGetCurrentSessionResponse(response GetCurrentSessionRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *GetCurrentSessionOKHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *Problem: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, span trace.Span) error { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(200) @@ -25,6 +227,366 @@ func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, s return nil } +func encodeLoginResponse(response LoginRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *SessionHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("Access-Control-Expose-Headers", "Set-Cookie") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + // Encode "Set-Cookie" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Set-Cookie", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(response.SetCookie)) + }); err != nil { + return errors.Wrap(err, "encode Set-Cookie header") + } + } + } + w.WriteHeader(201) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *LoginBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *LoginUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *LoginForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeLogoutResponse(response LogoutRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *LogoutNoContent: + w.Header().Set("Access-Control-Expose-Headers", "Set-Cookie") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Set-Cookie" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Set-Cookie", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(response.SetCookie)) + }); err != nil { + return errors.Wrap(err, "encode Set-Cookie header") + } + } + } + w.WriteHeader(204) + + return nil + + case *ProblemHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Set-Cookie") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Set-Cookie" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Set-Cookie", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(response.SetCookie)) + }); err != nil { + return errors.Wrap(err, "encode Set-Cookie header") + } + } + } + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *Problem: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeRegisterAccountResponse(response RegisterAccountRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *IdentityRequestAccepted: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(202) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RegisterAccountBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RegisterAccountForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RegisterAccountConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RegisterAccountUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeResendEmailVerificationResponse(response ResendEmailVerificationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *IdentityRequestAccepted: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(202) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ResendEmailVerificationBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ResendEmailVerificationForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeErrorResponse(response *ProblemStatusCode, w http.ResponseWriter, span trace.Span) error { w.Header().Set("Content-Type", "application/problem+json") code := response.StatusCode diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index 6c21a3a..2be152e 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -10,6 +10,24 @@ import ( "github.com/ogen-go/ogen/uri" ) +var ( + rn12AllowedHeaders = map[string]string{ + "POST": "Content-Type", + } + rn1AllowedHeaders = map[string]string{ + "POST": "Content-Type", + } + rn10AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key", + } + rn9AllowedHeaders = map[string]string{ + "POST": "Content-Type", + } + rn6AllowedHeaders = map[string]string{ + "DELETE": "X-Csrf-Token", + } +) + func (s *Server) cutPrefix(path string) (string, bool) { prefix := s.cfg.Prefix if prefix == "" { @@ -40,6 +58,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.notFound(w, r) return } + args := [1]string{} // Static code generated router with unwrapped path search. switch { @@ -48,29 +67,260 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { break } switch elem[0] { - case '/': // Prefix: "/api/v1/healthz" + case '/': // Prefix: "/api/v1/" - if l := len("/api/v1/healthz"); len(elem) >= l && elem[0:l] == "/api/v1/healthz" { + if l := len("/api/v1/"); len(elem) >= l && elem[0:l] == "/api/v1/" { elem = elem[l:] } else { break } if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "GET": - s.handleGetHealthzRequest([0]string{}, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET", - allowedHeaders: nil, - acceptPost: "", - acceptPatch: "", - }) + break + } + switch elem[0] { + case 'h': // Prefix: "healthz" + + if l := len("healthz"); len(elem) >= l && elem[0:l] == "healthz" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetHealthzRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + case 'i': // Prefix: "identity/" + + if l := len("identity/"); len(elem) >= l && elem[0:l] == "identity/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'c': // Prefix: "consent-texts/" + + if l := len("consent-texts/"); len(elem) >= l && elem[0:l] == "consent-texts/" { + elem = elem[l:] + } else { + break + } + + // Param: "purpose" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetConsentTextRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + case 'e': // Prefix: "email-verification" + + if l := len("email-verification"); len(elem) >= l && elem[0:l] == "email-verification" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case '-': // Prefix: "-requests" + + if l := len("-requests"); len(elem) >= l && elem[0:l] == "-requests" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleResendEmailVerificationRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn12AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + case 's': // Prefix: "s" + + if l := len("s"); len(elem) >= l && elem[0:l] == "s" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleConfirmEmailRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn1AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + } + + case 'm': // Prefix: "me" + + if l := len("me"); len(elem) >= l && elem[0:l] == "me" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetCurrentAccountRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + case 'r': // Prefix: "registrations" + + if l := len("registrations"); len(elem) >= l && elem[0:l] == "registrations" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleRegisterAccountRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn10AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + case 's': // Prefix: "sessions" + + if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "POST": + s.handleLoginRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn9AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/current" + + if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "DELETE": + s.handleLogoutRequest([0]string{}, elemIsEscaped, w, r) + case "GET": + s.handleGetCurrentSessionRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "DELETE,GET", + allowedHeaders: rn6AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + } - return } } @@ -86,7 +336,7 @@ type Route struct { operationGroup string pathPattern string count int - args [0]string + args [1]string } // Name returns ogen operation name. @@ -159,29 +409,265 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { break } switch elem[0] { - case '/': // Prefix: "/api/v1/healthz" + case '/': // Prefix: "/api/v1/" - if l := len("/api/v1/healthz"); len(elem) >= l && elem[0:l] == "/api/v1/healthz" { + if l := len("/api/v1/"); len(elem) >= l && elem[0:l] == "/api/v1/" { elem = elem[l:] } else { break } if len(elem) == 0 { - // Leaf node. - switch method { - case "GET": - r.name = GetHealthzOperation - r.summary = "Check whether the API process is responding." - r.operationID = "GetHealthz" - r.operationGroup = "" - r.pathPattern = "/api/v1/healthz" - r.args = args - r.count = 0 - return r, true - default: - return + break + } + switch elem[0] { + case 'h': // Prefix: "healthz" + + if l := len("healthz"); len(elem) >= l && elem[0:l] == "healthz" { + elem = elem[l:] + } else { + break } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetHealthzOperation + r.summary = "Check whether the API process is responding." + r.operationID = "GetHealthz" + r.operationGroup = "" + r.pathPattern = "/api/v1/healthz" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + case 'i': // Prefix: "identity/" + + if l := len("identity/"); len(elem) >= l && elem[0:l] == "identity/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'c': // Prefix: "consent-texts/" + + if l := len("consent-texts/"); len(elem) >= l && elem[0:l] == "consent-texts/" { + elem = elem[l:] + } else { + break + } + + // Param: "purpose" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetConsentTextOperation + r.summary = "Read the currently published text of a registration consent." + r.operationID = "GetConsentText" + r.operationGroup = "" + r.pathPattern = "/api/v1/identity/consent-texts/{purpose}" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 'e': // Prefix: "email-verification" + + if l := len("email-verification"); len(elem) >= l && elem[0:l] == "email-verification" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case '-': // Prefix: "-requests" + + if l := len("-requests"); len(elem) >= l && elem[0:l] == "-requests" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = ResendEmailVerificationOperation + r.summary = "Request a new email verification link." + r.operationID = "ResendEmailVerification" + r.operationGroup = "" + r.pathPattern = "/api/v1/identity/email-verification-requests" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + case 's': // Prefix: "s" + + if l := len("s"); len(elem) >= l && elem[0:l] == "s" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = ConfirmEmailOperation + r.summary = "Verify an email with the one-time token from the link." + r.operationID = "ConfirmEmail" + r.operationGroup = "" + r.pathPattern = "/api/v1/identity/email-verifications" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + } + + case 'm': // Prefix: "me" + + if l := len("me"); len(elem) >= l && elem[0:l] == "me" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetCurrentAccountOperation + r.summary = "Read the account of the current session." + r.operationID = "GetCurrentAccount" + r.operationGroup = "" + r.pathPattern = "/api/v1/identity/me" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + case 'r': // Prefix: "registrations" + + if l := len("registrations"); len(elem) >= l && elem[0:l] == "registrations" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = RegisterAccountOperation + r.summary = "Register an account by email with a scenario and consent C1." + r.operationID = "RegisterAccount" + r.operationGroup = "" + r.pathPattern = "/api/v1/identity/registrations" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + case 's': // Prefix: "sessions" + + if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "POST": + r.name = LoginOperation + r.summary = "Sign in with email and password and start a session." + r.operationID = "Login" + r.operationGroup = "" + r.pathPattern = "/api/v1/identity/sessions" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/current" + + if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "DELETE": + r.name = LogoutOperation + r.summary = "Sign out and revoke the current session." + r.operationID = "Logout" + r.operationGroup = "" + r.pathPattern = "/api/v1/identity/sessions/current" + r.args = args + r.count = 0 + return r, true + case "GET": + r.name = GetCurrentSessionOperation + r.summary = "Read the current session and its CSRF token." + r.operationID = "GetCurrentSession" + r.operationGroup = "" + r.pathPattern = "/api/v1/identity/sessions/current" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + } + + } + } } diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index ad772c7..9923e4a 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -4,14 +4,419 @@ package api import ( "fmt" + "time" "github.com/go-faster/errors" + "github.com/google/uuid" ) func (s *ProblemStatusCode) Error() string { return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response) } +// Current account view. It never contains password hashes, token hashes, session identifiers, or other +// storage secrets. +// Ref: #/components/schemas/Account +type Account struct { + // Account identifier. + ID uuid.UUID `json:"id"` + Email EmailAddress `json:"email"` + // Whether the address is verified. A session exists only for a verified account, so this is true in + // every current response. + EmailVerified bool `json:"email_verified"` + Scenario AccountScenario `json:"scenario"` + OnboardingStep OnboardingStep `json:"onboarding_step"` + CreatedAt Timestamp `json:"created_at"` +} + +// GetID returns the value of ID. +func (s *Account) GetID() uuid.UUID { + return s.ID +} + +// GetEmail returns the value of Email. +func (s *Account) GetEmail() EmailAddress { + return s.Email +} + +// GetEmailVerified returns the value of EmailVerified. +func (s *Account) GetEmailVerified() bool { + return s.EmailVerified +} + +// GetScenario returns the value of Scenario. +func (s *Account) GetScenario() AccountScenario { + return s.Scenario +} + +// GetOnboardingStep returns the value of OnboardingStep. +func (s *Account) GetOnboardingStep() OnboardingStep { + return s.OnboardingStep +} + +// GetCreatedAt returns the value of CreatedAt. +func (s *Account) GetCreatedAt() Timestamp { + return s.CreatedAt +} + +// SetID sets the value of ID. +func (s *Account) SetID(val uuid.UUID) { + s.ID = val +} + +// SetEmail sets the value of Email. +func (s *Account) SetEmail(val EmailAddress) { + s.Email = val +} + +// SetEmailVerified sets the value of EmailVerified. +func (s *Account) SetEmailVerified(val bool) { + s.EmailVerified = val +} + +// SetScenario sets the value of Scenario. +func (s *Account) SetScenario(val AccountScenario) { + s.Scenario = val +} + +// SetOnboardingStep sets the value of OnboardingStep. +func (s *Account) SetOnboardingStep(val OnboardingStep) { + s.OnboardingStep = val +} + +// SetCreatedAt sets the value of CreatedAt. +func (s *Account) SetCreatedAt(val Timestamp) { + s.CreatedAt = val +} + +// AccountHeaders wraps Account with response headers. +type AccountHeaders struct { + CacheControl CacheControlNoStore + Response Account +} + +// GetCacheControl returns the value of CacheControl. +func (s *AccountHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *AccountHeaders) GetResponse() Account { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *AccountHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *AccountHeaders) SetResponse(val Account) { + s.Response = val +} + +func (*AccountHeaders) getCurrentAccountRes() {} + +// Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, +// `employer` represents a company that searches for candidates. The scenario selects the onboarding +// steps. +// Ref: #/components/schemas/AccountScenario +type AccountScenario string + +const ( + AccountScenarioCandidate AccountScenario = "candidate" + AccountScenarioEmployer AccountScenario = "employer" +) + +// AllValues returns all AccountScenario values. +func (AccountScenario) AllValues() []AccountScenario { + return []AccountScenario{ + AccountScenarioCandidate, + AccountScenarioEmployer, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AccountScenario) MarshalText() ([]byte, error) { + switch s { + case AccountScenarioCandidate: + return []byte(s), nil + case AccountScenarioEmployer: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AccountScenario) UnmarshalText(data []byte) error { + switch AccountScenario(data) { + case AccountScenarioCandidate: + *s = AccountScenarioCandidate + return nil + case AccountScenarioEmployer: + *s = AccountScenarioEmployer + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type CacheControlNoStore string + +const ( + CacheControlNoStoreNoStore CacheControlNoStore = "no-store" +) + +// AllValues returns all CacheControlNoStore values. +func (CacheControlNoStore) AllValues() []CacheControlNoStore { + return []CacheControlNoStore{ + CacheControlNoStoreNoStore, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CacheControlNoStore) MarshalText() ([]byte, error) { + switch s { + case CacheControlNoStoreNoStore: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CacheControlNoStore) UnmarshalText(data []byte) error { + switch CacheControlNoStore(data) { + case CacheControlNoStoreNoStore: + *s = CacheControlNoStoreNoStore + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type ConfirmEmailBadRequest Problem + +func (*ConfirmEmailBadRequest) confirmEmailRes() {} + +type ConfirmEmailForbidden Problem + +func (*ConfirmEmailForbidden) confirmEmailRes() {} + +// Consent whose text the client may read before an account exists. Only the consents given at +// registration are listed: `c1` is the consent to the processing of personal data. +// Ref: #/components/schemas/ConsentPurpose +type ConsentPurpose string + +const ( + ConsentPurposeC1 ConsentPurpose = "c1" +) + +// AllValues returns all ConsentPurpose values. +func (ConsentPurpose) AllValues() []ConsentPurpose { + return []ConsentPurpose{ + ConsentPurposeC1, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ConsentPurpose) MarshalText() ([]byte, error) { + switch s { + case ConsentPurposeC1: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ConsentPurpose) UnmarshalText(data []byte) error { + switch ConsentPurpose(data) { + case ConsentPurposeC1: + *s = ConsentPurposeC1 + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Currently published consent text. The server stores an acceptance with `text_version` and the hash +// of exactly this text. +// Ref: #/components/schemas/ConsentText +type ConsentText struct { + Purpose ConsentPurpose `json:"purpose"` + TextVersion ConsentTextVersion `json:"text_version"` + // Full consent text in plain UTF-8; paragraphs are separated by an empty line. The client shows it as + // text, never as HTML. + Text string `json:"text"` + PublishedAt Timestamp `json:"published_at"` +} + +// GetPurpose returns the value of Purpose. +func (s *ConsentText) GetPurpose() ConsentPurpose { + return s.Purpose +} + +// GetTextVersion returns the value of TextVersion. +func (s *ConsentText) GetTextVersion() ConsentTextVersion { + return s.TextVersion +} + +// GetText returns the value of Text. +func (s *ConsentText) GetText() string { + return s.Text +} + +// GetPublishedAt returns the value of PublishedAt. +func (s *ConsentText) GetPublishedAt() Timestamp { + return s.PublishedAt +} + +// SetPurpose sets the value of Purpose. +func (s *ConsentText) SetPurpose(val ConsentPurpose) { + s.Purpose = val +} + +// SetTextVersion sets the value of TextVersion. +func (s *ConsentText) SetTextVersion(val ConsentTextVersion) { + s.TextVersion = val +} + +// SetText sets the value of Text. +func (s *ConsentText) SetText(val string) { + s.Text = val +} + +// SetPublishedAt sets the value of PublishedAt. +func (s *ConsentText) SetPublishedAt(val Timestamp) { + s.PublishedAt = val +} + +func (*ConsentText) getConsentTextRes() {} + +type ConsentTextVersion string + +type CsrfToken string + +type EmailAddress string + +// Token from the email verification link. +// Ref: #/components/schemas/EmailVerificationRequest +type EmailVerificationRequest struct { + Token VerificationToken `json:"token"` +} + +// GetToken returns the value of Token. +func (s *EmailVerificationRequest) GetToken() VerificationToken { + return s.Token +} + +// SetToken sets the value of Token. +func (s *EmailVerificationRequest) SetToken(val VerificationToken) { + s.Token = val +} + +// Address that should receive a new verification link. +// Ref: #/components/schemas/EmailVerificationResendRequest +type EmailVerificationResendRequest struct { + Email EmailAddress `json:"email"` +} + +// GetEmail returns the value of Email. +func (s *EmailVerificationResendRequest) GetEmail() EmailAddress { + return s.Email +} + +// SetEmail sets the value of Email. +func (s *EmailVerificationResendRequest) SetEmail(val EmailAddress) { + s.Email = val +} + +// Result of a successful email verification. It does not start a session; the user signs in next and +// continues from `onboarding_step`. +// Ref: #/components/schemas/EmailVerificationResult +type EmailVerificationResult struct { + // Always true in a successful response. + EmailVerified EmailVerificationResultEmailVerified `json:"email_verified"` + Scenario AccountScenario `json:"scenario"` + OnboardingStep OnboardingStep `json:"onboarding_step"` +} + +// GetEmailVerified returns the value of EmailVerified. +func (s *EmailVerificationResult) GetEmailVerified() EmailVerificationResultEmailVerified { + return s.EmailVerified +} + +// GetScenario returns the value of Scenario. +func (s *EmailVerificationResult) GetScenario() AccountScenario { + return s.Scenario +} + +// GetOnboardingStep returns the value of OnboardingStep. +func (s *EmailVerificationResult) GetOnboardingStep() OnboardingStep { + return s.OnboardingStep +} + +// SetEmailVerified sets the value of EmailVerified. +func (s *EmailVerificationResult) SetEmailVerified(val EmailVerificationResultEmailVerified) { + s.EmailVerified = val +} + +// SetScenario sets the value of Scenario. +func (s *EmailVerificationResult) SetScenario(val AccountScenario) { + s.Scenario = val +} + +// SetOnboardingStep sets the value of OnboardingStep. +func (s *EmailVerificationResult) SetOnboardingStep(val OnboardingStep) { + s.OnboardingStep = val +} + +func (*EmailVerificationResult) confirmEmailRes() {} + +// Always true in a successful response. +type EmailVerificationResultEmailVerified bool + +const ( + EmailVerificationResultEmailVerifiedTrue EmailVerificationResultEmailVerified = true +) + +// AllValues returns all EmailVerificationResultEmailVerified values. +func (EmailVerificationResultEmailVerified) AllValues() []EmailVerificationResultEmailVerified { + return []EmailVerificationResultEmailVerified{ + EmailVerificationResultEmailVerifiedTrue, + } +} + +// GetCurrentSessionOKHeaders wraps Session with response headers. +type GetCurrentSessionOKHeaders struct { + CacheControl CacheControlNoStore + Response Session +} + +// GetCacheControl returns the value of CacheControl. +func (s *GetCurrentSessionOKHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *GetCurrentSessionOKHeaders) GetResponse() Session { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *GetCurrentSessionOKHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *GetCurrentSessionOKHeaders) SetResponse(val Session) { + s.Response = val +} + +func (*GetCurrentSessionOKHeaders) getCurrentSessionRes() {} + // Ref: #/components/schemas/HealthResponse type HealthResponse struct { Status HealthResponseStatus `json:"status"` @@ -61,6 +466,249 @@ func (s *HealthResponseStatus) UnmarshalText(data []byte) error { } } +// Neutral acknowledgement. Its content is identical whether or not the address belongs to an account +// or is already verified, so the response does not enumerate accounts. The client tells the user to +// check the mailbox. +// Ref: #/components/schemas/IdentityRequestAccepted +type IdentityRequestAccepted struct { + Status IdentityRequestAcceptedStatus `json:"status"` +} + +// GetStatus returns the value of Status. +func (s *IdentityRequestAccepted) GetStatus() IdentityRequestAcceptedStatus { + return s.Status +} + +// SetStatus sets the value of Status. +func (s *IdentityRequestAccepted) SetStatus(val IdentityRequestAcceptedStatus) { + s.Status = val +} + +func (*IdentityRequestAccepted) registerAccountRes() {} +func (*IdentityRequestAccepted) resendEmailVerificationRes() {} + +type IdentityRequestAcceptedStatus string + +const ( + IdentityRequestAcceptedStatusAccepted IdentityRequestAcceptedStatus = "accepted" +) + +// AllValues returns all IdentityRequestAcceptedStatus values. +func (IdentityRequestAcceptedStatus) AllValues() []IdentityRequestAcceptedStatus { + return []IdentityRequestAcceptedStatus{ + IdentityRequestAcceptedStatusAccepted, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s IdentityRequestAcceptedStatus) MarshalText() ([]byte, error) { + switch s { + case IdentityRequestAcceptedStatusAccepted: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *IdentityRequestAcceptedStatus) UnmarshalText(data []byte) error { + switch IdentityRequestAcceptedStatus(data) { + case IdentityRequestAcceptedStatusAccepted: + *s = IdentityRequestAcceptedStatusAccepted + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type LoginBadRequest Problem + +func (*LoginBadRequest) loginRes() {} + +type LoginForbidden Problem + +func (*LoginForbidden) loginRes() {} + +type LoginPassword string + +// Email and password of the account. +// Ref: #/components/schemas/LoginRequest +type LoginRequest struct { + Email EmailAddress `json:"email"` + Password LoginPassword `json:"password"` +} + +// GetEmail returns the value of Email. +func (s *LoginRequest) GetEmail() EmailAddress { + return s.Email +} + +// GetPassword returns the value of Password. +func (s *LoginRequest) GetPassword() LoginPassword { + return s.Password +} + +// SetEmail sets the value of Email. +func (s *LoginRequest) SetEmail(val EmailAddress) { + s.Email = val +} + +// SetPassword sets the value of Password. +func (s *LoginRequest) SetPassword(val LoginPassword) { + s.Password = val +} + +type LoginUnauthorized Problem + +func (*LoginUnauthorized) loginRes() {} + +// LogoutNoContent is response for Logout operation. +type LogoutNoContent struct { + SetCookie string +} + +// GetSetCookie returns the value of SetCookie. +func (s *LogoutNoContent) GetSetCookie() string { + return s.SetCookie +} + +// SetSetCookie sets the value of SetCookie. +func (s *LogoutNoContent) SetSetCookie(val string) { + s.SetCookie = val +} + +func (*LogoutNoContent) logoutRes() {} + +type NewPassword string + +// Saved onboarding step that the account returns to after login. The server stores it and advances it +// as each step completes; clients route by it and never set it directly. +// +// - candidate_consents: candidate consents beyond C1, which was given at registration. +// - candidate_profile: candidate profile. +// - candidate_questionnaire: candidate questionnaire. +// - candidate_assessment: choice of the expected grade and the assessment. +// - employer_company: company profile of the employer. +// - completed: onboarding is finished; the client opens the scenario home. +// +// Candidate steps follow the order above and end with completed; the employer has employer_company and +// then completed. New steps may be added as onboarding grows; adding a value is a contract change. +// Ref: #/components/schemas/OnboardingStep +type OnboardingStep string + +const ( + OnboardingStepCandidateConsents OnboardingStep = "candidate_consents" + OnboardingStepCandidateProfile OnboardingStep = "candidate_profile" + OnboardingStepCandidateQuestionnaire OnboardingStep = "candidate_questionnaire" + OnboardingStepCandidateAssessment OnboardingStep = "candidate_assessment" + OnboardingStepEmployerCompany OnboardingStep = "employer_company" + OnboardingStepCompleted OnboardingStep = "completed" +) + +// AllValues returns all OnboardingStep values. +func (OnboardingStep) AllValues() []OnboardingStep { + return []OnboardingStep{ + OnboardingStepCandidateConsents, + OnboardingStepCandidateProfile, + OnboardingStepCandidateQuestionnaire, + OnboardingStepCandidateAssessment, + OnboardingStepEmployerCompany, + OnboardingStepCompleted, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s OnboardingStep) MarshalText() ([]byte, error) { + switch s { + case OnboardingStepCandidateConsents: + return []byte(s), nil + case OnboardingStepCandidateProfile: + return []byte(s), nil + case OnboardingStepCandidateQuestionnaire: + return []byte(s), nil + case OnboardingStepCandidateAssessment: + return []byte(s), nil + case OnboardingStepEmployerCompany: + return []byte(s), nil + case OnboardingStepCompleted: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *OnboardingStep) UnmarshalText(data []byte) error { + switch OnboardingStep(data) { + case OnboardingStepCandidateConsents: + *s = OnboardingStepCandidateConsents + return nil + case OnboardingStepCandidateProfile: + *s = OnboardingStepCandidateProfile + return nil + case OnboardingStepCandidateQuestionnaire: + *s = OnboardingStepCandidateQuestionnaire + return nil + case OnboardingStepCandidateAssessment: + *s = OnboardingStepCandidateAssessment + return nil + case OnboardingStepEmployerCompany: + *s = OnboardingStepEmployerCompany + return nil + case OnboardingStepCompleted: + *s = OnboardingStepCompleted + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// NewOptInt32 returns new OptInt32 with value set to v. +func NewOptInt32(v int32) OptInt32 { + return OptInt32{ + Value: v, + Set: true, + } +} + +// OptInt32 is optional int32. +type OptInt32 struct { + Value int32 + Set bool +} + +// IsSet returns true if OptInt32 was set. +func (o OptInt32) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptInt32) Reset() { + var v int32 + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptInt32) SetTo(v int32) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptInt32) Get() (v int32, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptInt32) Or(d int32) int32 { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewOptString returns new OptString with value set to v. func NewOptString(v string) OptString { return OptString{ @@ -107,6 +755,53 @@ func (o OptString) Or(d string) string { return d } +// Consent C1 to the processing of personal data, given at registration. The client reads the current +// text and its version with GetConsentText(c1) and sends that version here. A version that is not the +// currently published one answers 400 validation_failed with the pointer `/consent_c1/text_version`; +// the client then reads the text again and asks the user to accept the new version. Unknown fields are +// rejected, so registration cannot carry any other consent; in particular, C4 is never part of +// registration. +// Ref: #/components/schemas/PersonalDataConsentAcceptance +type PersonalDataConsentAcceptance struct { + TextVersion ConsentTextVersion `json:"text_version"` + // Explicit acceptance. Only true is valid. + Accepted PersonalDataConsentAcceptanceAccepted `json:"accepted"` +} + +// GetTextVersion returns the value of TextVersion. +func (s *PersonalDataConsentAcceptance) GetTextVersion() ConsentTextVersion { + return s.TextVersion +} + +// GetAccepted returns the value of Accepted. +func (s *PersonalDataConsentAcceptance) GetAccepted() PersonalDataConsentAcceptanceAccepted { + return s.Accepted +} + +// SetTextVersion sets the value of TextVersion. +func (s *PersonalDataConsentAcceptance) SetTextVersion(val ConsentTextVersion) { + s.TextVersion = val +} + +// SetAccepted sets the value of Accepted. +func (s *PersonalDataConsentAcceptance) SetAccepted(val PersonalDataConsentAcceptanceAccepted) { + s.Accepted = val +} + +// Explicit acceptance. Only true is valid. +type PersonalDataConsentAcceptanceAccepted bool + +const ( + PersonalDataConsentAcceptanceAcceptedTrue PersonalDataConsentAcceptanceAccepted = true +) + +// AllValues returns all PersonalDataConsentAcceptanceAccepted values. +func (PersonalDataConsentAcceptanceAccepted) AllValues() []PersonalDataConsentAcceptanceAccepted { + return []PersonalDataConsentAcceptanceAccepted{ + PersonalDataConsentAcceptanceAcceptedTrue, + } +} + // Problem details (RFC 9457) returned with the application/problem+json media type for every error // response. `code` is the stable, machine-readable reason; clients branch on it rather than on // `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack @@ -213,13 +908,27 @@ func (s *Problem) SetErrors(val []ProblemFieldError) { s.Errors = val } +func (*Problem) getConsentTextRes() {} +func (*Problem) getCurrentAccountRes() {} +func (*Problem) getCurrentSessionRes() {} +func (*Problem) logoutRes() {} + // Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking // change. Clients must handle an unknown code by its HTTP status. // // - validation_failed (400): parameters or body do not match the contract, or a body violates a // domain rule such as salary_from <= salary_to; `errors` points at the fields. +// - verification_token_invalid (400): the email verification token is unknown, already used, or +// replaced by a newer one; request a new link or sign in. +// - verification_token_expired (400): the email verification token is past its lifetime; request a +// new link. // - unauthenticated (401): no valid session or credentials. +// - invalid_credentials (401): the email and password do not match an account; an unknown email and a +// wrong password are not distinguished. // - forbidden (403): the caller is authenticated but not allowed. +// - email_not_verified (403): the credentials are correct but the email is not verified yet. +// - csrf_check_failed (403): the request failed cross-site request protection: a missing or wrong +// X-CSRF-Token or a disallowed Origin. // - not_found (404): the route or object does not exist or is not visible. // - method_not_allowed (405): the route does not support the method. // - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. @@ -238,29 +947,39 @@ func (s *Problem) SetErrors(val []ProblemFieldError) { type ProblemCode string const ( - ProblemCodeValidationFailed ProblemCode = "validation_failed" - ProblemCodeUnauthenticated ProblemCode = "unauthenticated" - ProblemCodeForbidden ProblemCode = "forbidden" - ProblemCodeNotFound ProblemCode = "not_found" - ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed" - ProblemCodeIdempotencyInProgress ProblemCode = "idempotency_in_progress" - ProblemCodeStateConflict ProblemCode = "state_conflict" - ProblemCodeVersionConflict ProblemCode = "version_conflict" - ProblemCodePayloadTooLarge ProblemCode = "payload_too_large" - ProblemCodeUnsupportedMediaType ProblemCode = "unsupported_media_type" - ProblemCodeIdempotencyKeyReused ProblemCode = "idempotency_key_reused" - ProblemCodePreconditionRequired ProblemCode = "precondition_required" - ProblemCodeRateLimited ProblemCode = "rate_limited" - ProblemCodeInternal ProblemCode = "internal" - ProblemCodeNotImplemented ProblemCode = "not_implemented" + ProblemCodeValidationFailed ProblemCode = "validation_failed" + ProblemCodeVerificationTokenInvalid ProblemCode = "verification_token_invalid" + ProblemCodeVerificationTokenExpired ProblemCode = "verification_token_expired" + ProblemCodeUnauthenticated ProblemCode = "unauthenticated" + ProblemCodeInvalidCredentials ProblemCode = "invalid_credentials" + ProblemCodeForbidden ProblemCode = "forbidden" + ProblemCodeEmailNotVerified ProblemCode = "email_not_verified" + ProblemCodeCsrfCheckFailed ProblemCode = "csrf_check_failed" + ProblemCodeNotFound ProblemCode = "not_found" + ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed" + ProblemCodeIdempotencyInProgress ProblemCode = "idempotency_in_progress" + ProblemCodeStateConflict ProblemCode = "state_conflict" + ProblemCodeVersionConflict ProblemCode = "version_conflict" + ProblemCodePayloadTooLarge ProblemCode = "payload_too_large" + ProblemCodeUnsupportedMediaType ProblemCode = "unsupported_media_type" + ProblemCodeIdempotencyKeyReused ProblemCode = "idempotency_key_reused" + ProblemCodePreconditionRequired ProblemCode = "precondition_required" + ProblemCodeRateLimited ProblemCode = "rate_limited" + ProblemCodeInternal ProblemCode = "internal" + ProblemCodeNotImplemented ProblemCode = "not_implemented" ) // AllValues returns all ProblemCode values. func (ProblemCode) AllValues() []ProblemCode { return []ProblemCode{ ProblemCodeValidationFailed, + ProblemCodeVerificationTokenInvalid, + ProblemCodeVerificationTokenExpired, ProblemCodeUnauthenticated, + ProblemCodeInvalidCredentials, ProblemCodeForbidden, + ProblemCodeEmailNotVerified, + ProblemCodeCsrfCheckFailed, ProblemCodeNotFound, ProblemCodeMethodNotAllowed, ProblemCodeIdempotencyInProgress, @@ -281,10 +1000,20 @@ func (s ProblemCode) MarshalText() ([]byte, error) { switch s { case ProblemCodeValidationFailed: return []byte(s), nil + case ProblemCodeVerificationTokenInvalid: + return []byte(s), nil + case ProblemCodeVerificationTokenExpired: + return []byte(s), nil case ProblemCodeUnauthenticated: return []byte(s), nil + case ProblemCodeInvalidCredentials: + return []byte(s), nil case ProblemCodeForbidden: return []byte(s), nil + case ProblemCodeEmailNotVerified: + return []byte(s), nil + case ProblemCodeCsrfCheckFailed: + return []byte(s), nil case ProblemCodeNotFound: return []byte(s), nil case ProblemCodeMethodNotAllowed: @@ -320,12 +1049,27 @@ func (s *ProblemCode) UnmarshalText(data []byte) error { case ProblemCodeValidationFailed: *s = ProblemCodeValidationFailed return nil + case ProblemCodeVerificationTokenInvalid: + *s = ProblemCodeVerificationTokenInvalid + return nil + case ProblemCodeVerificationTokenExpired: + *s = ProblemCodeVerificationTokenExpired + return nil case ProblemCodeUnauthenticated: *s = ProblemCodeUnauthenticated return nil + case ProblemCodeInvalidCredentials: + *s = ProblemCodeInvalidCredentials + return nil case ProblemCodeForbidden: *s = ProblemCodeForbidden return nil + case ProblemCodeEmailNotVerified: + *s = ProblemCodeEmailNotVerified + return nil + case ProblemCodeCsrfCheckFailed: + *s = ProblemCodeCsrfCheckFailed + return nil case ProblemCodeNotFound: *s = ProblemCodeNotFound return nil @@ -486,6 +1230,34 @@ func (s *ProblemFieldLocation) UnmarshalText(data []byte) error { } } +// ProblemHeaders wraps Problem with response headers. +type ProblemHeaders struct { + SetCookie string + Response Problem +} + +// GetSetCookie returns the value of SetCookie. +func (s *ProblemHeaders) GetSetCookie() string { + return s.SetCookie +} + +// GetResponse returns the value of Response. +func (s *ProblemHeaders) GetResponse() Problem { + return s.Response +} + +// SetSetCookie sets the value of SetCookie. +func (s *ProblemHeaders) SetSetCookie(val string) { + s.SetCookie = val +} + +// SetResponse sets the value of Response. +func (s *ProblemHeaders) SetResponse(val Problem) { + s.Response = val +} + +func (*ProblemHeaders) logoutRes() {} + // ProblemStatusCode wraps Problem with StatusCode. type ProblemStatusCode struct { StatusCode int @@ -511,3 +1283,228 @@ func (s *ProblemStatusCode) SetStatusCode(val int) { func (s *ProblemStatusCode) SetResponse(val Problem) { s.Response = val } + +type RegisterAccountBadRequest Problem + +func (*RegisterAccountBadRequest) registerAccountRes() {} + +type RegisterAccountConflict Problem + +func (*RegisterAccountConflict) registerAccountRes() {} + +type RegisterAccountForbidden Problem + +func (*RegisterAccountForbidden) registerAccountRes() {} + +type RegisterAccountUnprocessableEntity Problem + +func (*RegisterAccountUnprocessableEntity) registerAccountRes() {} + +// New account with its scenario and consent C1. +// Ref: #/components/schemas/RegistrationRequest +type RegistrationRequest struct { + Email EmailAddress `json:"email"` + Password NewPassword `json:"password"` + Scenario AccountScenario `json:"scenario"` + ConsentC1 PersonalDataConsentAcceptance `json:"consent_c1"` +} + +// GetEmail returns the value of Email. +func (s *RegistrationRequest) GetEmail() EmailAddress { + return s.Email +} + +// GetPassword returns the value of Password. +func (s *RegistrationRequest) GetPassword() NewPassword { + return s.Password +} + +// GetScenario returns the value of Scenario. +func (s *RegistrationRequest) GetScenario() AccountScenario { + return s.Scenario +} + +// GetConsentC1 returns the value of ConsentC1. +func (s *RegistrationRequest) GetConsentC1() PersonalDataConsentAcceptance { + return s.ConsentC1 +} + +// SetEmail sets the value of Email. +func (s *RegistrationRequest) SetEmail(val EmailAddress) { + s.Email = val +} + +// SetPassword sets the value of Password. +func (s *RegistrationRequest) SetPassword(val NewPassword) { + s.Password = val +} + +// SetScenario sets the value of Scenario. +func (s *RegistrationRequest) SetScenario(val AccountScenario) { + s.Scenario = val +} + +// SetConsentC1 sets the value of ConsentC1. +func (s *RegistrationRequest) SetConsentC1(val PersonalDataConsentAcceptance) { + s.ConsentC1 = val +} + +type ResendEmailVerificationBadRequest Problem + +func (*ResendEmailVerificationBadRequest) resendEmailVerificationRes() {} + +type ResendEmailVerificationForbidden Problem + +func (*ResendEmailVerificationForbidden) resendEmailVerificationRes() {} + +// Current session as the client may see it: the account and the CSRF token. The session identifier +// itself travels only in the HttpOnly session cookie and never appears in a body. +// Ref: #/components/schemas/Session +type Session struct { + Account Account `json:"account"` + CsrfToken CsrfToken `json:"csrf_token"` +} + +// GetAccount returns the value of Account. +func (s *Session) GetAccount() Account { + return s.Account +} + +// GetCsrfToken returns the value of CsrfToken. +func (s *Session) GetCsrfToken() CsrfToken { + return s.CsrfToken +} + +// SetAccount sets the value of Account. +func (s *Session) SetAccount(val Account) { + s.Account = val +} + +// SetCsrfToken sets the value of CsrfToken. +func (s *Session) SetCsrfToken(val CsrfToken) { + s.CsrfToken = val +} + +type SessionCookie struct { + APIKey string + Roles []string +} + +// GetAPIKey returns the value of APIKey. +func (s *SessionCookie) GetAPIKey() string { + return s.APIKey +} + +// GetRoles returns the value of Roles. +func (s *SessionCookie) GetRoles() []string { + return s.Roles +} + +// SetAPIKey sets the value of APIKey. +func (s *SessionCookie) SetAPIKey(val string) { + s.APIKey = val +} + +// SetRoles sets the value of Roles. +func (s *SessionCookie) SetRoles(val []string) { + s.Roles = val +} + +type SessionCsrf struct { + APIKey string + Roles []string +} + +// GetAPIKey returns the value of APIKey. +func (s *SessionCsrf) GetAPIKey() string { + return s.APIKey +} + +// GetRoles returns the value of Roles. +func (s *SessionCsrf) GetRoles() []string { + return s.Roles +} + +// SetAPIKey sets the value of APIKey. +func (s *SessionCsrf) SetAPIKey(val string) { + s.APIKey = val +} + +// SetRoles sets the value of Roles. +func (s *SessionCsrf) SetRoles(val []string) { + s.Roles = val +} + +// SessionHeaders wraps Session with response headers. +type SessionHeaders struct { + CacheControl CacheControlNoStore + SetCookie string + Response Session +} + +// GetCacheControl returns the value of CacheControl. +func (s *SessionHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetSetCookie returns the value of SetCookie. +func (s *SessionHeaders) GetSetCookie() string { + return s.SetCookie +} + +// GetResponse returns the value of Response. +func (s *SessionHeaders) GetResponse() Session { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *SessionHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetSetCookie sets the value of SetCookie. +func (s *SessionHeaders) SetSetCookie(val string) { + s.SetCookie = val +} + +// SetResponse sets the value of Response. +func (s *SessionHeaders) SetResponse(val Session) { + s.Response = val +} + +func (*SessionHeaders) loginRes() {} + +type Timestamp time.Time + +// TooManyRequestsHeaders wraps Problem with response headers. +type TooManyRequestsHeaders struct { + RetryAfter OptInt32 + Response Problem +} + +// GetRetryAfter returns the value of RetryAfter. +func (s *TooManyRequestsHeaders) GetRetryAfter() OptInt32 { + return s.RetryAfter +} + +// GetResponse returns the value of Response. +func (s *TooManyRequestsHeaders) GetResponse() Problem { + return s.Response +} + +// SetRetryAfter sets the value of RetryAfter. +func (s *TooManyRequestsHeaders) SetRetryAfter(val OptInt32) { + s.RetryAfter = val +} + +// SetResponse sets the value of Response. +func (s *TooManyRequestsHeaders) SetResponse(val Problem) { + s.Response = val +} + +func (*TooManyRequestsHeaders) confirmEmailRes() {} +func (*TooManyRequestsHeaders) loginRes() {} +func (*TooManyRequestsHeaders) registerAccountRes() {} +func (*TooManyRequestsHeaders) resendEmailVerificationRes() {} + +type VerificationToken string diff --git a/backend/internal/adapter/primary/http/api/oas_security_gen.go b/backend/internal/adapter/primary/http/api/oas_security_gen.go new file mode 100644 index 0000000..0021bc5 --- /dev/null +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -0,0 +1,150 @@ +// Code generated by ogen, DO NOT EDIT. + +package api + +import ( + "context" + "net/http" + "strings" + + "github.com/go-faster/errors" + "github.com/ogen-go/ogen/ogenerrors" +) + +// SecurityHandler is handler for security parameters. +type SecurityHandler interface { + // HandleSessionCookie handles sessionCookie security. + // Opaque random session identifier issued by Login in an HttpOnly cookie with + // `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain. The server keeps the session in + // PostgreSQL, checks its expiry and revocation on every request, and derives the caller from it; + // operations never take a user identifier from the body. A session ends after an idle timeout of 24 + // hours or an absolute lifetime of 7 days, whichever comes first (planned values from configuration); + // activity extends only the idle deadline. A missing, unknown, expired, or revoked session answers 401 + // unauthenticated. Scripts cannot read the cookie, and it never appears in a body, log, or problem. + // + // SameSite=Strict costs the single-page application nothing: its HTML is public and every API call is + // a same-origin fetch, which carries the cookie even right after a cross-site navigation, while + // cross-site requests never carry it. + HandleSessionCookie(ctx context.Context, operationName OperationName, t SessionCookie) (context.Context, error) + // HandleSessionCsrf handles sessionCsrf security. + // Synchronizer token bound to the session, returned by Login and GetCurrentSession. Every mutating + // operation that requires a session also requires this header; a missing token or one that does not + // belong to the session answers 403 csrf_check_failed. The token is defense in depth next to + // SameSite=Strict and the Origin check: every unsafe request (POST, PUT, PATCH, DELETE), including + // public ones such as Login, must carry an Origin from the configured allowlist, otherwise it answers + // 403 csrf_check_failed; a missing Origin is rejected too, and the server never derives the allowed + // Origin from the Host header. Request bodies are accepted only as application/json, which a + // cross-site form cannot send. A backend test requires every unsafe operation that requires + // sessionCookie to require this scheme as well. + HandleSessionCsrf(ctx context.Context, operationName OperationName, t SessionCsrf) (context.Context, error) +} + +func findAuthorization(h http.Header, prefix string) (string, bool) { + v, ok := h["Authorization"] + if !ok { + return "", false + } + for _, vv := range v { + scheme, value, ok := strings.Cut(vv, " ") + if !ok || !strings.EqualFold(scheme, prefix) { + continue + } + return value, true + } + return "", false +} + +// operationRolesSessionCookie is a private map storing roles per operation. +var operationRolesSessionCookie = map[string][]string{ + GetCurrentAccountOperation: []string{}, + GetCurrentSessionOperation: []string{}, + LogoutOperation: []string{}, +} + +// GetRolesForSessionCookie returns the required roles for the given operation. +// +// This is useful for authorization scenarios where you need to know which roles +// are required for an operation. +// +// Example: +// +// requiredRoles := GetRolesForSessionCookie(AddPetOperation) +// +// Returns nil if the operation has no role requirements or if the operation is unknown. +func GetRolesForSessionCookie(operation string) []string { + roles, ok := operationRolesSessionCookie[operation] + if !ok { + return nil + } + // Return a copy to prevent external modification + result := make([]string, len(roles)) + copy(result, roles) + return result +} + +// operationRolesSessionCsrf is a private map storing roles per operation. +var operationRolesSessionCsrf = map[string][]string{ + LogoutOperation: []string{}, +} + +// GetRolesForSessionCsrf returns the required roles for the given operation. +// +// This is useful for authorization scenarios where you need to know which roles +// are required for an operation. +// +// Example: +// +// requiredRoles := GetRolesForSessionCsrf(AddPetOperation) +// +// Returns nil if the operation has no role requirements or if the operation is unknown. +func GetRolesForSessionCsrf(operation string) []string { + roles, ok := operationRolesSessionCsrf[operation] + if !ok { + return nil + } + // Return a copy to prevent external modification + result := make([]string, len(roles)) + copy(result, roles) + return result +} + +func (s *Server) securitySessionCookie(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) { + var t SessionCookie + const parameterName = "__Host-lincodex_session" + var value string + switch cookie, err := req.Cookie(parameterName); { + case err == nil: // if NO error + value = cookie.Value + case errors.Is(err, http.ErrNoCookie): + return ctx, false, nil + default: + return nil, false, errors.Wrap(err, "get cookie value") + } + t.APIKey = value + t.Roles = operationRolesSessionCookie[operationName] + rctx, err := s.sec.HandleSessionCookie(ctx, operationName, t) + if errors.Is(err, ogenerrors.ErrSkipServerSecurity) { + return nil, false, nil + } else if err != nil { + return nil, false, err + } + return rctx, true, err +} + +func (s *Server) securitySessionCsrf(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) { + var t SessionCsrf + const parameterName = "X-CSRF-Token" + value := req.Header.Get(parameterName) + if value == "" { + return ctx, false, nil + } + t.APIKey = value + t.Roles = operationRolesSessionCsrf[operationName] + rctx, err := s.sec.HandleSessionCsrf(ctx, operationName, t) + if errors.Is(err, ogenerrors.ErrSkipServerSecurity) { + return nil, false, nil + } else if err != nil { + return nil, false, err + } + return rctx, true, err +} diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index b3935a6..73c49b8 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -8,12 +8,162 @@ import ( // Handler handles operations described by OpenAPI v3 specification. type Handler interface { + // ConfirmEmail implements ConfirmEmail operation. + // + // Public operation without a session. The verification link has the form + // `/verify-email#token=`: the token travels in the URL fragment, so it never + // reaches a server log or a Referer header. The page first removes the fragment with + // `history.replaceState`, then waits for an explicit user action, such as a Confirm button, before it + // posts the token here. A link scanner that only fetches the page therefore does not consume the + // token. + // + // The server looks up the token by its hash and, in one transaction, checks that it is unused, not + // expired, and bound to the current registration version, marks it used, and marks the email verified. + // Only one of several parallel requests with the same token succeeds. An expired token answers + // verification_token_expired; an unknown, used, replaced, or superseded token answers + // verification_token_invalid; neither changes anything. For both, the client offers a new link and + // sign-in, because the address may already be verified. + // + // A repeated confirmation with an already used token is not an idempotent 200: exactly one request may + // succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after + // either outcome is sign-in anyway. + // + // Success does not start a session: the link may be opened on another device or by a mail scanner, and + // a session must come only from the password. The response returns the scenario and the saved + // onboarding step so the client can continue after sign-in. The operation is rate-limited and requires + // an allowed Origin. + // + // POST /api/v1/identity/email-verifications + ConfirmEmail(ctx context.Context, req *EmailVerificationRequest) (ConfirmEmailRes, error) + // GetConsentText implements GetConsentText operation. + // + // Public operation without a session. Returns the current text of a consent that is given before an + // account exists; only `c1` is available. The registration page shows this text and sends its + // `text_version` with RegisterAccount, and the server hashes the same stored text when it records the + // acceptance. If the text changes while the page is open, RegisterAccount answers 400 + // validation_failed with the pointer `/consent_c1/text_version`, and the page reads the text again. An + // unknown purpose fails parameter validation with 400. + // + // GET /api/v1/identity/consent-texts/{purpose} + GetConsentText(ctx context.Context, params GetConsentTextParams) (GetConsentTextRes, error) + // GetCurrentAccount implements GetCurrentAccount operation. + // + // Requires the session cookie. The account comes from the session, never from a request parameter. The + // client uses `scenario` and `onboarding_step` to return the user to the unfinished onboarding step. A + // missing, unknown, expired, or revoked session answers 401 unauthenticated. An unverified account + // never has a session, because login answers 403 email_not_verified for it, so this operation also + // answers 401 for such an account. + // + // GET /api/v1/identity/me + GetCurrentAccount(ctx context.Context) (GetCurrentAccountRes, error) + // GetCurrentSession implements GetCurrentSession operation. + // + // Requires the session cookie. Returns the account and the CSRF token of the current session, so the + // client can restore the token after a page reload or after 403 csrf_check_failed. A missing, unknown, + // expired, or revoked session answers 401 unauthenticated. Cross-origin pages cannot read the token, + // because the API sends no Access-Control-Allow-Origin header. + // + // GET /api/v1/identity/sessions/current + GetCurrentSession(ctx context.Context) (GetCurrentSessionRes, error) // GetHealthz implements GetHealthz operation. // // Check whether the API process is responding. // // GET /api/v1/healthz GetHealthz(ctx context.Context) (*HealthResponse, error) + // Login implements Login operation. + // + // Public operation that starts a server session. The server verifies the password with Argon2id; for + // an unknown email it verifies against a fixed dummy hash, so the response time does not reveal + // whether the account exists. An unknown email and a wrong password both answer 401 + // invalid_credentials. + // + // Correct credentials for an unverified email answer 403 email_not_verified and create no session. + // This reveals the verification state only to someone who already knows the password, which proves + // more than the state itself; the client offers to resend the link. + // + // On success the server revokes the session that the request carried, if any, creates a new random + // session in PostgreSQL with a new identifier and a new CSRF token, sets the HttpOnly session cookie, + // and returns the account and the CSRF token. The new session follows the idle and absolute timeouts + // of the sessionCookie scheme. The client keeps the token in memory and sends it in X-CSRF-Token with + // every mutating request that requires a session. + // + // Login is rate-limited per client and per email and answers 429 with Retry-After. Like every unsafe + // request, it requires an allowed Origin, which protects against login CSRF, and answers 403 + // csrf_check_failed otherwise. + // + // POST /api/v1/identity/sessions + Login(ctx context.Context, req *LoginRequest) (LoginRes, error) + // Logout implements Logout operation. + // + // Requires the session cookie and the CSRF token of that session in X-CSRF-Token, and an allowed + // Origin. The server revokes the session in PostgreSQL, so the cookie value stops working even if a + // copy remains, and clears the cookie. A missing, expired, or revoked session answers 401 + // unauthenticated and also clears the cookie, so a stale cookie does not stay in the browser; a + // missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed and keeps the + // session and the cookie. The client clears its private query cache after the response. + // + // DELETE /api/v1/identity/sessions/current + Logout(ctx context.Context) (LogoutRes, error) + // RegisterAccount implements RegisterAccount operation. + // + // Public operation without a session. The client reads the current C1 text with GetConsentText and + // sends the email, the password, the chosen scenario, and consent C1 with the version of the text the + // user accepted. + // + // The answer is the same 202 whether the email is new, registered but not verified, or verified, so + // registration does not enumerate accounts: + // + // - New email: the server creates an unverified account with the scenario and the first onboarding + // step, records C1 with its text version and text hash, stores only the hash of a one-time + // verification token, and queues the verification message, all in one transaction. + // - Registered but not verified: the server treats the request as a new registration of that address. + // In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1 + // record, advances the registration version, invalidates every earlier verification token, and + // queues a message with a new token. A pre-registration with someone else's password therefore + // never survives the address owner's own registration. + // - Verified: nothing changes. The server may queue a rate-limited "you already have an account" + // notice to the address. + // + // Every verification token is bound to the registration version it was issued for, so a token issued + // before a re-registration can never confirm the newer credentials. An account that stays unverified + // is deleted with its consent record and tokens 7 days after its last registration (planned value from + // configuration). Verification tokens live 24 hours (planned value from configuration). + // + // The response does not depend on the branch in content or timing. Before it looks up the email, the + // server validates the whole body, including the password bounds after normalization, the password + // blocklist, and the C1 version, and it computes the Argon2id hash on every branch; a 400 therefore + // never depends on whether the email exists. Mail is delivered asynchronously from the outbox. + // + // The operation requires Idempotency-Key. For this anonymous operation the key is scoped by the + // operation, the key, and an HMAC of the normalized email, and the request fingerprint is an + // HMAC-SHA-256 with a server secret over the canonical JSON body. The server never stores the body, + // the password, or a plain hash of either; the secret keeps the fingerprint from serving as an offline + // password check. A retry with the same key, email, and body replays the stored 202 without a second + // message; the same key and email with a different body answers 422 idempotency_key_reused. + // + // It is rate-limited per client and per email and answers 429 with Retry-After when the limit is + // reached. Like every unsafe request, it requires an allowed Origin and answers 403 csrf_check_failed + // otherwise. + // + // POST /api/v1/identity/registrations + RegisterAccount(ctx context.Context, req *RegistrationRequest, params RegisterAccountParams) (RegisterAccountRes, error) + // ResendEmailVerification implements ResendEmailVerification operation. + // + // Public operation without a session. The answer is the same 202 for an unknown email, a verified + // email, and an unverified one, so it does not enumerate accounts. Only for an unverified account does + // the server issue a new one-time token bound to the current registration version, invalidate every + // earlier token of that account, and queue the message. Resend never changes the password, the + // scenario, or the consent record; a user who did not start the pending registration registers again + // instead, which replaces it. + // + // It is rate-limited per client and per email and answers 429 with Retry-After when the limit is + // reached. A retry is safe without Idempotency-Key: at worst it replaces the token again within the + // rate limit. Like every unsafe request, it requires an allowed Origin and answers 403 + // csrf_check_failed otherwise. + // + // POST /api/v1/identity/email-verification-requests + ResendEmailVerification(ctx context.Context, req *EmailVerificationResendRequest) (ResendEmailVerificationRes, error) // NewError creates *ProblemStatusCode from error returned by handler. // // Used for common default response. @@ -23,18 +173,20 @@ type Handler interface { // Server implements http server based on OpenAPI v3 specification and // calls Handler to handle requests. type Server struct { - h Handler + h Handler + sec SecurityHandler baseServer } // NewServer creates new Server. -func NewServer(h Handler, opts ...ServerOption) (*Server, error) { +func NewServer(h Handler, sec SecurityHandler, opts ...ServerOption) (*Server, error) { s, err := newServerConfig(opts...).baseServer() if err != nil { return nil, err } return &Server{ h: h, + sec: sec, baseServer: s, }, nil } diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 590da62..9e83fbf 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -13,6 +13,75 @@ type UnimplementedHandler struct{} var _ Handler = UnimplementedHandler{} +// ConfirmEmail implements ConfirmEmail operation. +// +// Public operation without a session. The verification link has the form +// `/verify-email#token=`: the token travels in the URL fragment, so it never +// reaches a server log or a Referer header. The page first removes the fragment with +// `history.replaceState`, then waits for an explicit user action, such as a Confirm button, before it +// posts the token here. A link scanner that only fetches the page therefore does not consume the +// token. +// +// The server looks up the token by its hash and, in one transaction, checks that it is unused, not +// expired, and bound to the current registration version, marks it used, and marks the email verified. +// Only one of several parallel requests with the same token succeeds. An expired token answers +// verification_token_expired; an unknown, used, replaced, or superseded token answers +// verification_token_invalid; neither changes anything. For both, the client offers a new link and +// sign-in, because the address may already be verified. +// +// A repeated confirmation with an already used token is not an idempotent 200: exactly one request may +// succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after +// either outcome is sign-in anyway. +// +// Success does not start a session: the link may be opened on another device or by a mail scanner, and +// a session must come only from the password. The response returns the scenario and the saved +// onboarding step so the client can continue after sign-in. The operation is rate-limited and requires +// an allowed Origin. +// +// POST /api/v1/identity/email-verifications +func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerificationRequest) (r ConfirmEmailRes, _ error) { + return r, ht.ErrNotImplemented +} + +// GetConsentText implements GetConsentText operation. +// +// Public operation without a session. Returns the current text of a consent that is given before an +// account exists; only `c1` is available. The registration page shows this text and sends its +// `text_version` with RegisterAccount, and the server hashes the same stored text when it records the +// acceptance. If the text changes while the page is open, RegisterAccount answers 400 +// validation_failed with the pointer `/consent_c1/text_version`, and the page reads the text again. An +// unknown purpose fails parameter validation with 400. +// +// GET /api/v1/identity/consent-texts/{purpose} +func (UnimplementedHandler) GetConsentText(ctx context.Context, params GetConsentTextParams) (r GetConsentTextRes, _ error) { + return r, ht.ErrNotImplemented +} + +// GetCurrentAccount implements GetCurrentAccount operation. +// +// Requires the session cookie. The account comes from the session, never from a request parameter. The +// client uses `scenario` and `onboarding_step` to return the user to the unfinished onboarding step. A +// missing, unknown, expired, or revoked session answers 401 unauthenticated. An unverified account +// never has a session, because login answers 403 email_not_verified for it, so this operation also +// answers 401 for such an account. +// +// GET /api/v1/identity/me +func (UnimplementedHandler) GetCurrentAccount(ctx context.Context) (r GetCurrentAccountRes, _ error) { + return r, ht.ErrNotImplemented +} + +// GetCurrentSession implements GetCurrentSession operation. +// +// Requires the session cookie. Returns the account and the CSRF token of the current session, so the +// client can restore the token after a page reload or after 403 csrf_check_failed. A missing, unknown, +// expired, or revoked session answers 401 unauthenticated. Cross-origin pages cannot read the token, +// because the API sends no Access-Control-Allow-Origin header. +// +// GET /api/v1/identity/sessions/current +func (UnimplementedHandler) GetCurrentSession(ctx context.Context) (r GetCurrentSessionRes, _ error) { + return r, ht.ErrNotImplemented +} + // GetHealthz implements GetHealthz operation. // // Check whether the API process is responding. @@ -22,6 +91,111 @@ func (UnimplementedHandler) GetHealthz(ctx context.Context) (r *HealthResponse, return r, ht.ErrNotImplemented } +// Login implements Login operation. +// +// Public operation that starts a server session. The server verifies the password with Argon2id; for +// an unknown email it verifies against a fixed dummy hash, so the response time does not reveal +// whether the account exists. An unknown email and a wrong password both answer 401 +// invalid_credentials. +// +// Correct credentials for an unverified email answer 403 email_not_verified and create no session. +// This reveals the verification state only to someone who already knows the password, which proves +// more than the state itself; the client offers to resend the link. +// +// On success the server revokes the session that the request carried, if any, creates a new random +// session in PostgreSQL with a new identifier and a new CSRF token, sets the HttpOnly session cookie, +// and returns the account and the CSRF token. The new session follows the idle and absolute timeouts +// of the sessionCookie scheme. The client keeps the token in memory and sends it in X-CSRF-Token with +// every mutating request that requires a session. +// +// Login is rate-limited per client and per email and answers 429 with Retry-After. Like every unsafe +// request, it requires an allowed Origin, which protects against login CSRF, and answers 403 +// csrf_check_failed otherwise. +// +// POST /api/v1/identity/sessions +func (UnimplementedHandler) Login(ctx context.Context, req *LoginRequest) (r LoginRes, _ error) { + return r, ht.ErrNotImplemented +} + +// Logout implements Logout operation. +// +// Requires the session cookie and the CSRF token of that session in X-CSRF-Token, and an allowed +// Origin. The server revokes the session in PostgreSQL, so the cookie value stops working even if a +// copy remains, and clears the cookie. A missing, expired, or revoked session answers 401 +// unauthenticated and also clears the cookie, so a stale cookie does not stay in the browser; a +// missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed and keeps the +// session and the cookie. The client clears its private query cache after the response. +// +// DELETE /api/v1/identity/sessions/current +func (UnimplementedHandler) Logout(ctx context.Context) (r LogoutRes, _ error) { + return r, ht.ErrNotImplemented +} + +// RegisterAccount implements RegisterAccount operation. +// +// Public operation without a session. The client reads the current C1 text with GetConsentText and +// sends the email, the password, the chosen scenario, and consent C1 with the version of the text the +// user accepted. +// +// The answer is the same 202 whether the email is new, registered but not verified, or verified, so +// registration does not enumerate accounts: +// +// - New email: the server creates an unverified account with the scenario and the first onboarding +// step, records C1 with its text version and text hash, stores only the hash of a one-time +// verification token, and queues the verification message, all in one transaction. +// - Registered but not verified: the server treats the request as a new registration of that address. +// In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1 +// record, advances the registration version, invalidates every earlier verification token, and +// queues a message with a new token. A pre-registration with someone else's password therefore +// never survives the address owner's own registration. +// - Verified: nothing changes. The server may queue a rate-limited "you already have an account" +// notice to the address. +// +// Every verification token is bound to the registration version it was issued for, so a token issued +// before a re-registration can never confirm the newer credentials. An account that stays unverified +// is deleted with its consent record and tokens 7 days after its last registration (planned value from +// configuration). Verification tokens live 24 hours (planned value from configuration). +// +// The response does not depend on the branch in content or timing. Before it looks up the email, the +// server validates the whole body, including the password bounds after normalization, the password +// blocklist, and the C1 version, and it computes the Argon2id hash on every branch; a 400 therefore +// never depends on whether the email exists. Mail is delivered asynchronously from the outbox. +// +// The operation requires Idempotency-Key. For this anonymous operation the key is scoped by the +// operation, the key, and an HMAC of the normalized email, and the request fingerprint is an +// HMAC-SHA-256 with a server secret over the canonical JSON body. The server never stores the body, +// the password, or a plain hash of either; the secret keeps the fingerprint from serving as an offline +// password check. A retry with the same key, email, and body replays the stored 202 without a second +// message; the same key and email with a different body answers 422 idempotency_key_reused. +// +// It is rate-limited per client and per email and answers 429 with Retry-After when the limit is +// reached. Like every unsafe request, it requires an allowed Origin and answers 403 csrf_check_failed +// otherwise. +// +// POST /api/v1/identity/registrations +func (UnimplementedHandler) RegisterAccount(ctx context.Context, req *RegistrationRequest, params RegisterAccountParams) (r RegisterAccountRes, _ error) { + return r, ht.ErrNotImplemented +} + +// ResendEmailVerification implements ResendEmailVerification operation. +// +// Public operation without a session. The answer is the same 202 for an unknown email, a verified +// email, and an unverified one, so it does not enumerate accounts. Only for an unverified account does +// the server issue a new one-time token bound to the current registration version, invalidate every +// earlier token of that account, and queue the message. Resend never changes the password, the +// scenario, or the consent record; a user who did not start the pending registration registers again +// instead, which replaces it. +// +// It is rate-limited per client and per email and answers 429 with Retry-After when the limit is +// reached. A retry is safe without Idempotency-Key: at worst it replaces the token again within the +// rate limit. Like every unsafe request, it requires an allowed Origin and answers 403 +// csrf_check_failed otherwise. +// +// POST /api/v1/identity/email-verification-requests +func (UnimplementedHandler) ResendEmailVerification(ctx context.Context, req *EmailVerificationResendRequest) (r ResendEmailVerificationRes, _ error) { + return r, ht.ErrNotImplemented +} + // NewError creates *ProblemStatusCode from error returned by handler. // // Used for common default response. diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index 3081e2d..58ce294 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -9,6 +9,381 @@ import ( "github.com/ogen-go/ogen/validate" ) +func (s *Account) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Email.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "email", + Error: err, + }) + } + if err := func() error { + if err := s.Scenario.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "scenario", + Error: err, + }) + } + if err := func() error { + if err := s.OnboardingStep.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "onboarding_step", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AccountHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AccountScenario) Validate() error { + switch s { + case "candidate": + return nil + case "employer": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s CacheControlNoStore) Validate() error { + switch s { + case "no-store": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ConfirmEmailBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ConfirmEmailForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s ConsentPurpose) Validate() error { + switch s { + case "c1": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ConsentText) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Purpose.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "purpose", + Error: err, + }) + } + if err := func() error { + if err := s.TextVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "text_version", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 100000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Text)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "text", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ConsentTextVersion) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 64, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s CsrfToken) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 32, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9_-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s EmailAddress) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 3, + MinLengthSet: true, + MaxLength: 254, + MaxLengthSet: true, + Email: true, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *EmailVerificationRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Token.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "token", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *EmailVerificationResendRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Email.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "email", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *EmailVerificationResult) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.EmailVerified.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "email_verified", + Error: err, + }) + } + if err := func() error { + if err := s.Scenario.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "scenario", + Error: err, + }) + } + if err := func() error { + if err := s.OnboardingStep.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "onboarding_step", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s EmailVerificationResultEmailVerified) Validate() error { + switch s { + case true: + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *GetCurrentSessionOKHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *HealthResponse) Validate() error { if s == nil { return validate.ErrNilPointer @@ -41,6 +416,233 @@ func (s HealthResponseStatus) Validate() error { } } +func (s *IdentityRequestAccepted) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s IdentityRequestAcceptedStatus) Validate() error { + switch s { + case "accepted": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *LoginBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *LoginForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s LoginPassword) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *LoginRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Email.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "email", + Error: err, + }) + } + if err := func() error { + if err := s.Password.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "password", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *LoginUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *LogoutNoContent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4096, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^__Host-lincodex_session="], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.SetCookie)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "SetCookie", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s NewPassword) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 15, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s OnboardingStep) Validate() error { + switch s { + case "candidate_consents": + return nil + case "candidate_profile": + return nil + case "candidate_questionnaire": + return nil + case "candidate_assessment": + return nil + case "employer_company": + return nil + case "completed": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *PersonalDataConsentAcceptance) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.TextVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "text_version", + Error: err, + }) + } + if err := func() error { + if err := s.Accepted.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "accepted", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s PersonalDataConsentAcceptanceAccepted) Validate() error { + switch s { + case true: + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *Problem) Validate() error { if s == nil { return validate.ErrNilPointer @@ -261,10 +863,20 @@ func (s ProblemCode) Validate() error { switch s { case "validation_failed": return nil + case "verification_token_invalid": + return nil + case "verification_token_expired": + return nil case "unauthenticated": return nil + case "invalid_credentials": + return nil case "forbidden": return nil + case "email_not_verified": + return nil + case "csrf_check_failed": + return nil case "not_found": return nil case "method_not_allowed": @@ -403,6 +1015,52 @@ func (s ProblemFieldLocation) Validate() error { } } +func (s *ProblemHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4096, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^__Host-lincodex_session="], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.SetCookie)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "SetCookie", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *ProblemStatusCode) Validate() error { if s == nil { return validate.ErrNilPointer @@ -425,3 +1083,269 @@ func (s *ProblemStatusCode) Validate() error { } return nil } + +func (s *RegisterAccountBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RegisterAccountConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RegisterAccountForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RegisterAccountUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RegistrationRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Email.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "email", + Error: err, + }) + } + if err := func() error { + if err := s.Password.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "password", + Error: err, + }) + } + if err := func() error { + if err := s.Scenario.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "scenario", + Error: err, + }) + } + if err := func() error { + if err := s.ConsentC1.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "consent_c1", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ResendEmailVerificationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ResendEmailVerificationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *Session) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Account.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "account", + Error: err, + }) + } + if err := func() error { + if err := s.CsrfToken.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "csrf_token", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *SessionHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4096, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^__Host-lincodex_session="], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.SetCookie)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "SetCookie", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *TooManyRequestsHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if value, ok := s.RetryAfter.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 86400, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "RetryAfter", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s VerificationToken) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 32, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9_-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} diff --git a/backend/internal/adapter/primary/http/problem/problem.go b/backend/internal/adapter/primary/http/problem/problem.go index bb703c9..a1fc2da 100644 --- a/backend/internal/adapter/primary/http/problem/problem.go +++ b/backend/internal/adapter/primary/http/problem/problem.go @@ -32,16 +32,41 @@ var definitions = map[api.ProblemCode]definition{ title: "Request validation failed", detail: "One or more request fields are invalid.", }, + api.ProblemCodeVerificationTokenInvalid: { + status: http.StatusBadRequest, + title: "Verification link is not valid", + detail: "Request a new verification link, or sign in if the address is already verified.", + }, + api.ProblemCodeVerificationTokenExpired: { + status: http.StatusBadRequest, + title: "Verification link expired", + detail: "Request a new verification link.", + }, api.ProblemCodeUnauthenticated: { status: http.StatusUnauthorized, title: "Authentication required", detail: "Sign in and repeat the request.", }, + api.ProblemCodeInvalidCredentials: { + status: http.StatusUnauthorized, + title: "Invalid email or password", + detail: "Check the email and password and try again.", + }, api.ProblemCodeForbidden: { status: http.StatusForbidden, title: "Access denied", detail: "You do not have permission to perform this operation.", }, + api.ProblemCodeEmailNotVerified: { + status: http.StatusForbidden, + title: "Email not verified", + detail: "Confirm the email address with the link from the verification message.", + }, + api.ProblemCodeCsrfCheckFailed: { + status: http.StatusForbidden, + title: "Cross-site request check failed", + detail: "Read the current session to get a new CSRF token and repeat the request.", + }, api.ProblemCodeNotFound: { status: http.StatusNotFound, title: "Resource not found", diff --git a/backend/internal/adapter/primary/http/router.go b/backend/internal/adapter/primary/http/router.go index 056ac6c..2d4690d 100644 --- a/backend/internal/adapter/primary/http/router.go +++ b/backend/internal/adapter/primary/http/router.go @@ -26,16 +26,20 @@ const ( // ht.ErrNotImplemented to 501, request decoding and validation errors to 400, // unknown routes under /api to 404, unsupported methods to 405, and any other // server error or panic to 500 without exposing its text. Operation errors go -// through apiHandler.NewError. +// through apiHandler.NewError. security decides every operation that requires +// a session; the generated server answers its rejection, and a request +// without the session cookie, with 401 unauthenticated through NewError. func NewRouter( health *v1.HealthHandler, apiHandler apiadapter.Handler, + security apiadapter.SecurityHandler, problems *problem.Responder, collector httpmiddleware.RequestMetrics, logger *slog.Logger, ) (http.Handler, error) { apiServer, err := apiadapter.NewServer( apiHandler, + security, apiadapter.WithErrorHandler(problems.HandleServerError), apiadapter.WithNotFound(problems.NotFound), apiadapter.WithMethodNotAllowed(problems.MethodNotAllowed), diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index 925a945..e695af7 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -106,6 +106,311 @@ func TestPublicUnimplementedOperationReturnsNotImplementedProblem(t *testing.T) } } +// Identity request fixtures shared by the router tests. +const ( + testSessionCookie = "__Host-lincodex_session=opaque-session-value" + testCSRFToken = "Xk4pR9tV2mQ7wL1sN8bC5dF0gH3jZ6yA9eU2iO7rT4c" + testIdempotencyKey = "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11" + registrationPath = "/api/v1/identity/registrations" + currentSessionPath = "/api/v1/identity/sessions/current" +) + +// registrationBody returns a valid RegisterAccount body with replaced parts. +func registrationBody(password, consent string) string { + return `{"email":"candidate@example.com","password":"` + password + `","scenario":"candidate","consent_c1":` + consent + `}` +} + +const ( + validPassword = "correct horse battery staple" + validConsent = `{"text_version":"c1-2026-10-01","accepted":true}` +) + +type identityRequest struct { + method string + path string + body string + headers map[string]string +} + +func serveIdentityRequest(t *testing.T, router http.Handler, request identityRequest) *httptest.ResponseRecorder { + t.Helper() + httpRequest := httptest.NewRequest(request.method, request.path, strings.NewReader(request.body)) + if request.body != "" { + httpRequest.Header.Set("Content-Type", "application/json") + } + for name, value := range request.headers { + httpRequest.Header.Set(name, value) + } + response := httptest.NewRecorder() + router.ServeHTTP(response, httpRequest) + return response +} + +// Identity operations are in the contract before their business logic. Public +// ones must answer 501 only after request validation, and session-protected +// ones must stay closed: DenyAllSecurity grants no session, with or without a +// cookie and a CSRF token. +func TestIdentityOperationsBeforeImplementation(t *testing.T) { + for _, test := range []struct { + name string + request identityRequest + statusCode int + code api.ProblemCode + }{ + { + name: "public registration", + request: identityRequest{ + method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent), + headers: map[string]string{"Idempotency-Key": testIdempotencyKey}, + }, + statusCode: http.StatusNotImplemented, + code: api.ProblemCodeNotImplemented, + }, + { + name: "public email verification resend", + request: identityRequest{ + method: http.MethodPost, path: "/api/v1/identity/email-verification-requests", + body: `{"email":"candidate@example.com"}`, + }, + statusCode: http.StatusNotImplemented, + code: api.ProblemCodeNotImplemented, + }, + { + name: "public email confirmation", + request: identityRequest{ + method: http.MethodPost, path: "/api/v1/identity/email-verifications", + body: `{"token":"q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE"}`, + }, + statusCode: http.StatusNotImplemented, + code: api.ProblemCodeNotImplemented, + }, + { + name: "public login", + request: identityRequest{ + method: http.MethodPost, path: "/api/v1/identity/sessions", + body: `{"email":"candidate@example.com","password":"correct horse battery staple"}`, + }, + statusCode: http.StatusNotImplemented, + code: api.ProblemCodeNotImplemented, + }, + { + name: "public consent text", + request: identityRequest{method: http.MethodGet, path: "/api/v1/identity/consent-texts/c1"}, + statusCode: http.StatusNotImplemented, + code: api.ProblemCodeNotImplemented, + }, + { + name: "current account without a session cookie", + request: identityRequest{method: http.MethodGet, path: "/api/v1/identity/me"}, + statusCode: http.StatusUnauthorized, + code: api.ProblemCodeUnauthenticated, + }, + { + name: "current account with a session cookie", + request: identityRequest{ + method: http.MethodGet, path: "/api/v1/identity/me", + headers: map[string]string{"Cookie": testSessionCookie}, + }, + statusCode: http.StatusUnauthorized, + code: api.ProblemCodeUnauthenticated, + }, + { + name: "current session without a session cookie", + request: identityRequest{method: http.MethodGet, path: currentSessionPath}, + statusCode: http.StatusUnauthorized, + code: api.ProblemCodeUnauthenticated, + }, + { + name: "logout with a session cookie and a CSRF token", + request: identityRequest{ + method: http.MethodDelete, path: currentSessionPath, + headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}, + }, + statusCode: http.StatusUnauthorized, + code: api.ProblemCodeUnauthenticated, + }, + { + name: "logout with only a CSRF token", + request: identityRequest{ + method: http.MethodDelete, path: currentSessionPath, + headers: map[string]string{"X-CSRF-Token": testCSRFToken}, + }, + statusCode: http.StatusUnauthorized, + code: api.ProblemCodeUnauthenticated, + }, + { + name: "logout with only a session cookie", + request: identityRequest{ + method: http.MethodDelete, path: currentSessionPath, + headers: map[string]string{"Cookie": testSessionCookie}, + }, + statusCode: http.StatusUnauthorized, + code: api.ProblemCodeUnauthenticated, + }, + } { + t.Run(test.name, func(t *testing.T) { + router := newTestRouter(t, func(context.Context) error { return nil }) + response := serveIdentityRequest(t, router, test.request) + + requireProblem(t, response, test.statusCode, test.code) + if cookie := response.Header().Get("Set-Cookie"); test.statusCode == http.StatusNotImplemented && cookie != "" { + t.Fatalf("Set-Cookie = %q, want none from an unimplemented operation", cookie) + } + }) + } + + // The security handler does not affect operations without security. + router := newTestRouter(t, func(context.Context) error { return nil }) + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) + if response.Code != http.StatusOK { + t.Fatalf("healthz status code = %d, want %d: %s", response.Code, http.StatusOK, response.Body.String()) + } +} + +// Registration rejects invalid requests with 400 before the 501 of the +// missing business logic, with pointers to the failing fields. +func TestRegistrationValidationPrecedesImplementation(t *testing.T) { + const fourteenCharacters = "fourteen-chars" + withKey := map[string]string{"Idempotency-Key": testIdempotencyKey} + for _, test := range []struct { + name string + body string + headers map[string]string + location api.ProblemFieldLocation + pointer string + code string + }{ + { + // Unknown fields are rejected, so no other consent, such as C4, + // can be given at registration. + name: "consent C4 at registration", + body: `{"email":"candidate@example.com","password":"` + validPassword + `","scenario":"candidate","consent_c1":` + validConsent + `,"consent_c4":{"text_version":"c4-2026-10-01","accepted":true}}`, + headers: withKey, + location: api.ProblemFieldLocationBody, + pointer: "", + code: "invalid", + }, + { + name: "consent C1 not accepted", + body: registrationBody(validPassword, `{"text_version":"c1-2026-10-01","accepted":false}`), + headers: withKey, + location: api.ProblemFieldLocationBody, + pointer: "/consent_c1/accepted", + code: "invalid", + }, + { + name: "password shorter than 15 characters", + body: registrationBody(fourteenCharacters, validConsent), + headers: withKey, + location: api.ProblemFieldLocationBody, + pointer: "/password", + code: "invalid", + }, + { + name: "missing Idempotency-Key", + body: registrationBody(validPassword, validConsent), + location: api.ProblemFieldLocationHeader, + pointer: "/Idempotency-Key", + code: "required", + }, + } { + t.Run(test.name, func(t *testing.T) { + router := newTestRouter(t, func(context.Context) error { return nil }) + response := serveIdentityRequest(t, router, identityRequest{ + method: http.MethodPost, path: registrationPath, body: test.body, headers: test.headers, + }) + + body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed) + want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code} + for _, field := range body.Errors { + if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code { + return + } + } + t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want) + }) + } +} + +// sessionPrincipalKey marks the context returned by HandleSessionCookie. +type sessionPrincipalKey struct{} + +// recordingSecurity accepts every scheme value and records the order of the +// calls and whether HandleSessionCsrf saw the context of HandleSessionCookie. +type recordingSecurity struct { + calls []string + csrfSawPrincipal bool +} + +func (security *recordingSecurity) HandleSessionCookie(ctx context.Context, _ api.OperationName, _ api.SessionCookie) (context.Context, error) { + security.calls = append(security.calls, "SessionCookie") + return context.WithValue(ctx, sessionPrincipalKey{}, "principal"), nil +} + +func (security *recordingSecurity) HandleSessionCsrf(ctx context.Context, _ api.OperationName, _ api.SessionCsrf) (context.Context, error) { + security.calls = append(security.calls, "SessionCsrf") + security.csrfSawPrincipal = ctx.Value(sessionPrincipalKey{}) != nil + return ctx, nil +} + +// The session-bound CSRF check of TASK-056 relies on the generated server +// calling HandleSessionCookie before HandleSessionCsrf and passing the +// returned context on. ogen orders the calls by scheme name, so renaming a +// scheme or upgrading ogen must keep this test green. +func TestGeneratedServerSecurityOrder(t *testing.T) { + for _, test := range []struct { + name string + headers map[string]string + calls []string + csrfSawPrincipal bool + statusCode int + }{ + { + name: "cookie and CSRF token", + headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}, + calls: []string{"SessionCookie", "SessionCsrf"}, + csrfSawPrincipal: true, + statusCode: http.StatusNotImplemented, + }, + { + // Without a cookie HandleSessionCsrf still runs, with the + // original context, and the unsatisfied requirement answers 401. + name: "CSRF token without a cookie", + headers: map[string]string{"X-CSRF-Token": testCSRFToken}, + calls: []string{"SessionCsrf"}, + statusCode: http.StatusUnauthorized, + }, + { + name: "cookie without a CSRF token", + headers: map[string]string{"Cookie": testSessionCookie}, + calls: []string{"SessionCookie"}, + statusCode: http.StatusUnauthorized, + }, + } { + t.Run(test.name, func(t *testing.T) { + logger := slog.New(slog.DiscardHandler) + healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) + security := &recordingSecurity{} + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), security, problem.NewResponder(logger), metrics.New(), logger) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + response := serveIdentityRequest(t, router, identityRequest{method: http.MethodDelete, path: currentSessionPath, headers: test.headers}) + + if response.Code != test.statusCode { + t.Fatalf("status code = %d, want %d: %s", response.Code, test.statusCode, response.Body.String()) + } + if fmt.Sprint(security.calls) != fmt.Sprint(test.calls) { + t.Fatalf("security calls = %v, want %v", security.calls, test.calls) + } + if security.csrfSawPrincipal != test.csrfSawPrincipal { + t.Fatalf("HandleSessionCsrf saw the session context = %t, want %t", security.csrfSawPrincipal, test.csrfSawPrincipal) + } + }) + } +} + func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) { var logs bytes.Buffer logger := slog.New(slog.NewJSONHandler(&logs, nil)) @@ -154,7 +459,7 @@ func TestPublicOperationPanicReturnsInternalProblem(t *testing.T) { getHealthz: func(context.Context) (*api.HealthResponse, error) { panic(panicText) }, } recorder := &requestRecorder{} - router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), recorder, logger) + router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), recorder, logger) if err != nil { t.Fatalf("NewRouter() error = %v", err) } @@ -331,7 +636,7 @@ func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler { func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler, logger *slog.Logger) http.Handler { t.Helper() - router, err := NewRouter(healthHandler, apiHandler, problem.NewResponder(logger), metrics.New(), logger) + router, err := NewRouter(healthHandler, apiHandler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), metrics.New(), logger) if err != nil { t.Fatalf("NewRouter() error = %v", err) } @@ -343,7 +648,7 @@ func newOverrideRouterWithMetrics(t *testing.T, collector *requestRecorder, getH logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz} - router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), collector, logger) + router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), collector, logger) if err != nil { t.Fatalf("NewRouter() error = %v", err) } diff --git a/backend/internal/adapter/primary/http/security_contract_test.go b/backend/internal/adapter/primary/http/security_contract_test.go new file mode 100644 index 0000000..624b603 --- /dev/null +++ b/backend/internal/adapter/primary/http/security_contract_test.go @@ -0,0 +1,80 @@ +package httpadapter + +import ( + "net/http" + "os" + "slices" + "testing" + + "github.com/ogen-go/ogen" +) + +// publicContractBundle is the bundled public contract that the generated +// server is built from, relative to this package. +const publicContractBundle = "../../../../../api/core/openapi.bundle.yml" + +const ( + sessionCookieScheme = "sessionCookie" + sessionCSRFScheme = "sessionCsrf" +) + +// A browser sends the session cookie with every same-site request, so an +// unsafe operation that accepts the session must also demand the +// session-bound CSRF token. A new operation that forgets sessionCsrf would +// otherwise compile and pass every other check. +func TestUnsafeSessionOperationsRequireCSRFToken(t *testing.T) { + data, err := os.ReadFile(publicContractBundle) + if err != nil { + t.Fatalf("read the public contract bundle: %v", err) + } + spec, err := ogen.Parse(data) + if err != nil { + t.Fatalf("parse the public contract bundle: %v", err) + } + + checked := 0 + for path, item := range spec.Paths { + for method, operation := range unsafeOperations(item) { + // An operation without its own security list inherits the root + // one; an explicit empty list makes it public. + requirements := operation.Security + if requirements == nil { + requirements = spec.Security + } + for _, requirement := range requirements { + if _, usesSession := requirement[sessionCookieScheme]; !usesSession { + continue + } + checked++ + if _, usesCSRF := requirement[sessionCSRFScheme]; !usesCSRF { + t.Errorf("%s %s (%s) accepts %s without %s", method, path, operation.OperationID, sessionCookieScheme, sessionCSRFScheme) + } + } + } + } + // Logout is an unsafe session operation, so an empty result means the + // bundle was not read as expected. + if checked == 0 { + t.Fatal("found no unsafe operation that requires a session; the check would pass vacuously") + } +} + +func unsafeOperations(item *ogen.PathItem) map[string]*ogen.Operation { + operations := map[string]*ogen.Operation{ + http.MethodPost: item.Post, + http.MethodPut: item.Put, + http.MethodPatch: item.Patch, + http.MethodDelete: item.Delete, + } + for method, operation := range item.AdditionalOperations { + if !slices.Contains([]string{http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace}, method) { + operations[method] = operation + } + } + for method, operation := range operations { + if operation == nil { + delete(operations, method) + } + } + return operations +} diff --git a/backend/internal/adapter/primary/http/v1/security.go b/backend/internal/adapter/primary/http/v1/security.go new file mode 100644 index 0000000..a568529 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/security.go @@ -0,0 +1,70 @@ +package v1 + +import ( + "context" + "errors" + + "lincodex/backend/internal/adapter/primary/http/api" +) + +// errSessionsNotImplemented rejects every session-protected request until the +// session boundary exists. Its text stays in the server: the generated server +// wraps it in *ogenerrors.SecurityError, which the problem responder answers +// with a fixed 401 unauthenticated problem. +var errSessionsNotImplemented = errors.New("v1.DenyAllSecurity - sessions are not implemented") + +// DenyAllSecurity implements api.SecurityHandler by rejecting every session +// cookie and CSRF token, so no operation that requires a session is reachable +// before server sessions exist. Operations that declare `security: []` do not +// call it and keep their own behavior, which is 501 not_implemented until +// their business logic exists. +// +// TASK-056 replaces it. The generated server (ogen v1.24.0) evaluates the +// schemes of an operation as follows; TestGeneratedServerSecurityOrder pins +// the order and the context propagation: +// +// - It evaluates sessionCookie before sessionCsrf, in the order of the +// generated type names, and each step receives the context returned by +// the previous successful step. +// - A scheme whose value is absent (no cookie, or an empty X-CSRF-Token +// header) does not call its Handle method and counts as unsatisfied. +// - A Handle method that returns ogenerrors.ErrSkipServerSecurity also counts +// as unsatisfied, and evaluation continues with the next scheme. +// - A Handle method that returns any other error stops evaluation: the +// server passes &ogenerrors.SecurityError{Security: "SessionCookie" or +// "SessionCsrf", Err: err} to Handler.NewError with the context that the +// failing step received. HandleSessionCsrf is therefore called after a +// missing cookie or a skipped session, with the original context, but +// never after HandleSessionCookie returned another error. +// - When every scheme was evaluated and a requirement is still unsatisfied, +// the server passes &ogenerrors.SecurityError{Err: +// ogenerrors.ErrSecurityRequirementIsNotSatisfied}, without a Security +// field, to Handler.NewError with the context of the last successful step. +// +// The intended mapping on top of that behavior: +// +// - HandleSessionCookie returns a context with the principal for a valid +// session and ogenerrors.ErrSkipServerSecurity for a missing, unknown, +// expired, or revoked one. +// - HandleSessionCsrf returns ogenerrors.ErrSkipServerSecurity when the +// context has no principal, so the result is 401 unauthenticated, and a +// typed error when the token does not belong to the session. +// - NewError answers a SecurityError with Security "SessionCsrf" with 403 +// csrf_check_failed, an unsatisfied requirement whose context carries a +// principal (an empty X-CSRF-Token) with 403 csrf_check_failed, and every +// other security failure with 401 unauthenticated. +type DenyAllSecurity struct{} + +var _ api.SecurityHandler = (*DenyAllSecurity)(nil) + +func NewDenyAllSecurity() *DenyAllSecurity { + return &DenyAllSecurity{} +} + +func (*DenyAllSecurity) HandleSessionCookie(ctx context.Context, _ api.OperationName, _ api.SessionCookie) (context.Context, error) { + return ctx, errSessionsNotImplemented +} + +func (*DenyAllSecurity) HandleSessionCsrf(ctx context.Context, _ api.OperationName, _ api.SessionCsrf) (context.Context, error) { + return ctx, errSessionsNotImplemented +} diff --git a/backend/internal/adapter/secondary/ml/api/oas_json_gen.go b/backend/internal/adapter/secondary/ml/api/oas_json_gen.go index c7ae0f1..947067d 100644 --- a/backend/internal/adapter/secondary/ml/api/oas_json_gen.go +++ b/backend/internal/adapter/secondary/ml/api/oas_json_gen.go @@ -630,10 +630,20 @@ func (s *ProblemCode) Decode(d *jx.Decoder) error { switch ProblemCode(v) { case ProblemCodeValidationFailed: *s = ProblemCodeValidationFailed + case ProblemCodeVerificationTokenInvalid: + *s = ProblemCodeVerificationTokenInvalid + case ProblemCodeVerificationTokenExpired: + *s = ProblemCodeVerificationTokenExpired case ProblemCodeUnauthenticated: *s = ProblemCodeUnauthenticated + case ProblemCodeInvalidCredentials: + *s = ProblemCodeInvalidCredentials case ProblemCodeForbidden: *s = ProblemCodeForbidden + case ProblemCodeEmailNotVerified: + *s = ProblemCodeEmailNotVerified + case ProblemCodeCsrfCheckFailed: + *s = ProblemCodeCsrfCheckFailed case ProblemCodeNotFound: *s = ProblemCodeNotFound case ProblemCodeMethodNotAllowed: diff --git a/backend/internal/adapter/secondary/ml/api/oas_schemas_gen.go b/backend/internal/adapter/secondary/ml/api/oas_schemas_gen.go index 04f29fd..924f489 100644 --- a/backend/internal/adapter/secondary/ml/api/oas_schemas_gen.go +++ b/backend/internal/adapter/secondary/ml/api/oas_schemas_gen.go @@ -298,33 +298,46 @@ func (s *Problem) SetErrors(val []ProblemFieldError) { // - internal (500): unexpected server error. // - not_implemented (501): the operation is in the contract but not implemented yet. // +// The enum keeps the public API codes so both contracts share one Problem shape. The identity codes +// verification_token_invalid, verification_token_expired, invalid_credentials, email_not_verified, and +// csrf_check_failed belong to the public API; the ML service never returns them. // Ref: #/components/schemas/ProblemCode type ProblemCode string const ( - ProblemCodeValidationFailed ProblemCode = "validation_failed" - ProblemCodeUnauthenticated ProblemCode = "unauthenticated" - ProblemCodeForbidden ProblemCode = "forbidden" - ProblemCodeNotFound ProblemCode = "not_found" - ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed" - ProblemCodeIdempotencyInProgress ProblemCode = "idempotency_in_progress" - ProblemCodeStateConflict ProblemCode = "state_conflict" - ProblemCodeVersionConflict ProblemCode = "version_conflict" - ProblemCodePayloadTooLarge ProblemCode = "payload_too_large" - ProblemCodeUnsupportedMediaType ProblemCode = "unsupported_media_type" - ProblemCodeIdempotencyKeyReused ProblemCode = "idempotency_key_reused" - ProblemCodePreconditionRequired ProblemCode = "precondition_required" - ProblemCodeRateLimited ProblemCode = "rate_limited" - ProblemCodeInternal ProblemCode = "internal" - ProblemCodeNotImplemented ProblemCode = "not_implemented" + ProblemCodeValidationFailed ProblemCode = "validation_failed" + ProblemCodeVerificationTokenInvalid ProblemCode = "verification_token_invalid" + ProblemCodeVerificationTokenExpired ProblemCode = "verification_token_expired" + ProblemCodeUnauthenticated ProblemCode = "unauthenticated" + ProblemCodeInvalidCredentials ProblemCode = "invalid_credentials" + ProblemCodeForbidden ProblemCode = "forbidden" + ProblemCodeEmailNotVerified ProblemCode = "email_not_verified" + ProblemCodeCsrfCheckFailed ProblemCode = "csrf_check_failed" + ProblemCodeNotFound ProblemCode = "not_found" + ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed" + ProblemCodeIdempotencyInProgress ProblemCode = "idempotency_in_progress" + ProblemCodeStateConflict ProblemCode = "state_conflict" + ProblemCodeVersionConflict ProblemCode = "version_conflict" + ProblemCodePayloadTooLarge ProblemCode = "payload_too_large" + ProblemCodeUnsupportedMediaType ProblemCode = "unsupported_media_type" + ProblemCodeIdempotencyKeyReused ProblemCode = "idempotency_key_reused" + ProblemCodePreconditionRequired ProblemCode = "precondition_required" + ProblemCodeRateLimited ProblemCode = "rate_limited" + ProblemCodeInternal ProblemCode = "internal" + ProblemCodeNotImplemented ProblemCode = "not_implemented" ) // AllValues returns all ProblemCode values. func (ProblemCode) AllValues() []ProblemCode { return []ProblemCode{ ProblemCodeValidationFailed, + ProblemCodeVerificationTokenInvalid, + ProblemCodeVerificationTokenExpired, ProblemCodeUnauthenticated, + ProblemCodeInvalidCredentials, ProblemCodeForbidden, + ProblemCodeEmailNotVerified, + ProblemCodeCsrfCheckFailed, ProblemCodeNotFound, ProblemCodeMethodNotAllowed, ProblemCodeIdempotencyInProgress, @@ -345,10 +358,20 @@ func (s ProblemCode) MarshalText() ([]byte, error) { switch s { case ProblemCodeValidationFailed: return []byte(s), nil + case ProblemCodeVerificationTokenInvalid: + return []byte(s), nil + case ProblemCodeVerificationTokenExpired: + return []byte(s), nil case ProblemCodeUnauthenticated: return []byte(s), nil + case ProblemCodeInvalidCredentials: + return []byte(s), nil case ProblemCodeForbidden: return []byte(s), nil + case ProblemCodeEmailNotVerified: + return []byte(s), nil + case ProblemCodeCsrfCheckFailed: + return []byte(s), nil case ProblemCodeNotFound: return []byte(s), nil case ProblemCodeMethodNotAllowed: @@ -384,12 +407,27 @@ func (s *ProblemCode) UnmarshalText(data []byte) error { case ProblemCodeValidationFailed: *s = ProblemCodeValidationFailed return nil + case ProblemCodeVerificationTokenInvalid: + *s = ProblemCodeVerificationTokenInvalid + return nil + case ProblemCodeVerificationTokenExpired: + *s = ProblemCodeVerificationTokenExpired + return nil case ProblemCodeUnauthenticated: *s = ProblemCodeUnauthenticated return nil + case ProblemCodeInvalidCredentials: + *s = ProblemCodeInvalidCredentials + return nil case ProblemCodeForbidden: *s = ProblemCodeForbidden return nil + case ProblemCodeEmailNotVerified: + *s = ProblemCodeEmailNotVerified + return nil + case ProblemCodeCsrfCheckFailed: + *s = ProblemCodeCsrfCheckFailed + return nil case ProblemCodeNotFound: *s = ProblemCodeNotFound return nil diff --git a/backend/internal/adapter/secondary/ml/api/oas_validators_gen.go b/backend/internal/adapter/secondary/ml/api/oas_validators_gen.go index 9503c58..dee8792 100644 --- a/backend/internal/adapter/secondary/ml/api/oas_validators_gen.go +++ b/backend/internal/adapter/secondary/ml/api/oas_validators_gen.go @@ -311,10 +311,20 @@ func (s ProblemCode) Validate() error { switch s { case "validation_failed": return nil + case "verification_token_invalid": + return nil + case "verification_token_expired": + return nil case "unauthenticated": return nil + case "invalid_credentials": + return nil case "forbidden": return nil + case "email_not_verified": + return nil + case "csrf_check_failed": + return nil case "not_found": return nil case "method_not_allowed": diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index 0034561..9efc53b 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -31,11 +31,13 @@ func initialize(ctx context.Context, config config.Config, logger *slog.Logger) wire.Bind(new(inbound.Readiness), new(*health.Readiness)), wire.Bind(new(httpmiddleware.RequestMetrics), new(*metrics.Metrics)), wire.Bind(new(apiadapter.Handler), new(*v1.Handler)), + wire.Bind(new(apiadapter.SecurityHandler), new(*v1.DenyAllSecurity)), newReadiness, metrics.New, newHealthHandler, problem.NewResponder, v1.NewHandler, + v1.NewDenyAllSecurity, httpadapter.NewRouter, NewApplication, ), diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index 0fdd413..5957f04 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -43,8 +43,9 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger) healthHandler := newHealthHandler(readiness, config2) responder := problem.NewResponder(logger) handler := v1.NewHandler(healthHandler, responder) + denyAllSecurity := v1.NewDenyAllSecurity() metrics := prometheus.New() - httpHandler, err := httpadapter.NewRouter(healthHandler, handler, responder, metrics, logger) + httpHandler, err := httpadapter.NewRouter(healthHandler, handler, denyAllSecurity, responder, metrics, logger) if err != nil { cleanup3() cleanup2() diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index bcd6883..e99dabc 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -55,7 +55,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, consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, mail delivery, the Go Kafka client, the transactional outbox and its relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ has no business schema, product usecase and adapter directories 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, mail delivery, the Go Kafka client, the transactional outbox and its relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ has no business schema, product usecase and adapter directories 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 @@ -82,6 +82,12 @@ make check is not a business end-to-end suite. make verify runs a deployment smo Security tools have a separate install and work loop: `make -C security install`, then `make -C security check`. Use `make -C security test` after changing local rules or scanner integration and `make -C security images` to build and scan service images. These checks are separate from the ordinary root `make check`; see [SECURITY.md](SECURITY.md) for prerequisites, policies, and reports. +### Sessions on local HTTP + +The planned session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict` (see [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). The local stack serves plain HTTP. Chromium and Firefox treat `http://localhost` and `http://127.0.0.1` as secure contexts and keep a `Secure` cookie there; WebKit and Safari may reject it. Use Chromium or Firefox for local sign-in, or put a local TLS proxy in front. The project adds no flag that drops `Secure` or the `__Host-` prefix, so the local cookie never differs from production. + +Planned Origin rule (TASK-056): every unsafe request (POST, PUT, PATCH, DELETE), including public ones such as login, must carry an `Origin` from an allowlist in the backend configuration, for example the Nginx origin and the Vite dev origin. The server does not compare `Origin` with `Host`. An unsafe request without `Origin` or with another value answers 403 `csrf_check_failed`. + ## Layout Each top-level directory except `.github/` has a short Russian `README.md` and an English `README.en.md`. A README and its translation are optional in `.github/`. Detailed guides live in `docs/ru/` and `docs/en/`; READMEs are not added below the first directory level. `make docs-check` validates language pairs and links and runs the checker's own tests. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 60c8088..687abcf 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -55,7 +55,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-приложение пока не отправляет телеметрию. -Еще не реализованы: регистрация и вход, согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, transactional outbox и его relay, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, transactional outbox и его relay, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы @@ -82,6 +82,12 @@ make check не является бизнес-E2E проверкой. make verif У инструментов безопасности отдельный цикл установки и проверки: `make -C security install`, затем `make -C security check`. После изменения локальных правил или интеграции сканеров запускайте `make -C security test`; для сборки и сканирования образов сервисов - `make -C security images`. Эти проверки отделены от обычного корневого `make check`; требования, политика и отчеты описаны в [SECURITY.md](SECURITY.md). +### Сессии на локальном HTTP + +Запланированная cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `SameSite=Strict` (см. [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Локальный стек отдает обычный HTTP. Chromium и Firefox считают `http://localhost` и `http://127.0.0.1` безопасным контекстом и сохраняют там `Secure` cookie; WebKit и Safari могут ее отклонить. Для локального входа используйте Chromium или Firefox либо локальный TLS-прокси. Проект не добавляет флаг, отключающий `Secure` или префикс `__Host-`, поэтому локальная cookie не отличается от production. + +Запланированное правило Origin (TASK-056): любой небезопасный запрос (POST, PUT, PATCH, DELETE), включая публичные, например вход, должен нести `Origin` из allowlist в конфигурации backend, например origin Nginx и origin dev-сервера Vite. Сервер не сравнивает `Origin` с `Host`. Небезопасный запрос без `Origin` или с другим значением получает 403 `csrf_check_failed`. + ## Структура В каждом каталоге первого уровня, кроме `.github/`, есть краткий `README.md` на русском и его перевод `README.en.md`. В `.github/` README и его перевод необязательны. Подробные руководства находятся в `docs/ru/` и `docs/en/`; README глубже первого уровня не добавляются. `make docs-check` проверяет языковые пары, ссылки и запускает тесты самого проверяющего скрипта. diff --git a/frontend/codegen/orval.config.ts b/frontend/codegen/orval.config.ts index b1ad5cc..7909f2b 100644 --- a/frontend/codegen/orval.config.ts +++ b/frontend/codegen/orval.config.ts @@ -47,6 +47,11 @@ const inlineReusableResponses = defineTransformer((spec) => { // The API compatibility check sets this variable to a temporary directory to // generate the OpenAPI 3.2 fixture with the production settings. const compatOutput = process.env["ORVAL_COMPAT_OUTPUT"]; +// `clean: true` empties the output directories, so an empty value, which +// would place them at the filesystem root, is rejected. +if (compatOutput !== undefined && compatOutput.trim() === "") { + throw new Error("ORVAL_COMPAT_OUTPUT must name a directory when it is set."); +} function project(inputTarget: string, endpoints: string, schemas: string): Options { return { @@ -59,6 +64,11 @@ function project(inputTarget: string, endpoints: string, schemas: string): Optio output: { mode: "tags-split", target: endpoints, + // The endpoint and schema directories hold only generated files. A schema + // used by several tags moves from a tag directory to the schema root, so + // the directories are cleared first to drop files the contract no longer + // produces. + clean: true, indexFiles: true, // Generated operations take header parameters such as Idempotency-Key // and If-Match as a typed argument instead of dropping them. diff --git a/frontend/src/shared/api/endpoints/identity/identity.msw.ts b/frontend/src/shared/api/endpoints/identity/identity.msw.ts new file mode 100644 index 0000000..64d13fd --- /dev/null +++ b/frontend/src/shared/api/endpoints/identity/identity.msw.ts @@ -0,0 +1,150 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + faker +} from '@faker-js/faker'; + +import { + HttpResponse, + http +} from 'msw'; +import type { + RequestHandlerOptions +} from 'msw'; + +import { + AccountScenario, + ConsentPurpose, + OnboardingStep +} from '../../schemas'; +import type { + Account, + ConsentText, + EmailVerificationResult, + IdentityRequestAccepted, + Session +} from '../../schemas'; + + +export const getGetConsentTextResponseMock = (overrideResponse: Partial> = {}): ConsentText => ({purpose: faker.helpers.arrayElement(Object.values(ConsentPurpose)), text_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), text: faker.string.alpha({length: {min: 1, max: 100000}}), published_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) + +export const getRegisterAccountResponseMock = (overrideResponse: Partial> = {}): IdentityRequestAccepted => ({status: faker.helpers.arrayElement(['accepted'] as const), ...overrideResponse}) + +export const getResendEmailVerificationResponseMock = (overrideResponse: Partial> = {}): IdentityRequestAccepted => ({status: faker.helpers.arrayElement(['accepted'] as const), ...overrideResponse}) + +export const getConfirmEmailResponseMock = (overrideResponse: Partial> = {}): EmailVerificationResult => ({email_verified: faker.helpers.arrayElement([true] as const), scenario: faker.helpers.arrayElement(Object.values(AccountScenario)), onboarding_step: faker.helpers.arrayElement(Object.values(OnboardingStep)), ...overrideResponse}) + +export const getLoginResponseMock = (overrideResponse: Partial> = {}): Session => ({account: {id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(Object.values(AccountScenario)), onboarding_step: faker.helpers.arrayElement(Object.values(OnboardingStep)), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, csrf_token: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), ...overrideResponse}) + +export const getGetCurrentSessionResponseMock = (overrideResponse: Partial> = {}): Session => ({account: {id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(Object.values(AccountScenario)), onboarding_step: faker.helpers.arrayElement(Object.values(OnboardingStep)), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, csrf_token: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), ...overrideResponse}) + +export const getGetCurrentAccountResponseMock = (overrideResponse: Partial> = {}): Account => ({id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(Object.values(AccountScenario)), onboarding_step: faker.helpers.arrayElement(Object.values(OnboardingStep)), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) + + +export const getGetConsentTextMockHandler = (overrideResponse?: ConsentText | ((info: Parameters[1]>[0]) => Promise | ConsentText), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/identity/consent-texts/:purpose', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetConsentTextResponseMock(), + { status: 200 + }) + }, options) +} + +export const getRegisterAccountMockHandler = (overrideResponse?: IdentityRequestAccepted | ((info: Parameters[1]>[0]) => Promise | IdentityRequestAccepted), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/identity/registrations', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getRegisterAccountResponseMock(), + { status: 202 + }) + }, options) +} + +export const getResendEmailVerificationMockHandler = (overrideResponse?: IdentityRequestAccepted | ((info: Parameters[1]>[0]) => Promise | IdentityRequestAccepted), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/identity/email-verification-requests', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getResendEmailVerificationResponseMock(), + { status: 202 + }) + }, options) +} + +export const getConfirmEmailMockHandler = (overrideResponse?: EmailVerificationResult | ((info: Parameters[1]>[0]) => Promise | EmailVerificationResult), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/identity/email-verifications', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getConfirmEmailResponseMock(), + { status: 200 + }) + }, options) +} + +export const getLoginMockHandler = (overrideResponse?: Session | ((info: Parameters[1]>[0]) => Promise | Session), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/identity/sessions', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getLoginResponseMock(), + { status: 201 + }) + }, options) +} + +export const getGetCurrentSessionMockHandler = (overrideResponse?: Session | ((info: Parameters[1]>[0]) => Promise | Session), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/identity/sessions/current', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetCurrentSessionResponseMock(), + { status: 200 + }) + }, options) +} + +export const getLogoutMockHandler = (overrideResponse?: void | ((info: Parameters[1]>[0]) => Promise | void), options?: RequestHandlerOptions) => { + return http.delete('*/api/v1/identity/sessions/current', async (info: Parameters[1]>[0]) => { + if (typeof overrideResponse === 'function') {await overrideResponse(info); } + + return new HttpResponse(null, + { status: 204 + }) + }, options) +} + +export const getGetCurrentAccountMockHandler = (overrideResponse?: Account | ((info: Parameters[1]>[0]) => Promise | Account), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/identity/me', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetCurrentAccountResponseMock(), + { status: 200 + }) + }, options) +} +export const getIdentityMock = () => [ + getGetConsentTextMockHandler(), + getRegisterAccountMockHandler(), + getResendEmailVerificationMockHandler(), + getConfirmEmailMockHandler(), + getLoginMockHandler(), + getGetCurrentSessionMockHandler(), + getLogoutMockHandler(), + getGetCurrentAccountMockHandler() +] diff --git a/frontend/src/shared/api/endpoints/identity/identity.ts b/frontend/src/shared/api/endpoints/identity/identity.ts new file mode 100644 index 0000000..dbc8a33 --- /dev/null +++ b/frontend/src/shared/api/endpoints/identity/identity.ts @@ -0,0 +1,821 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + Account, + ConsentPurpose, + ConsentText, + EmailVerificationRequest, + EmailVerificationResendRequest, + EmailVerificationResult, + IdentityRequestAccepted, + LoginRequest, + Problem, + RegisterAccountHeaders, + RegistrationRequest, + Session +} from '../../schemas'; + +import { apiRequest } from '../../client'; +import type { ErrorType } from '../../client'; + + +type SecondParameter unknown> = Parameters[1]; + + + +const withQueryKey = (query: T, queryKey: K): T & { queryKey: K } => { + const result = { queryKey } as T & { queryKey: K }; + for (const key of Object.keys(query)) { + // The explicit queryKey always wins, matching the previous + // `{ ...query, queryKey }` spread where it was set last. + if (key === 'queryKey') continue; + Object.defineProperty(result, key, { + enumerable: true, + configurable: true, + get: () => (query as Record)[key], + }); + } + return result; +}; + +export const getGetConsentTextUrl = (purpose: ConsentPurpose,) => { + + + + + return `/api/v1/identity/consent-texts/${purpose}` +} + +/** + * Public operation without a session. Returns the current text of a consent that is given before an account exists; only `c1` is available. The registration page shows this text and sends its `text_version` with RegisterAccount, and the server hashes the same stored text when it records the acceptance. If the text changes while the page is open, RegisterAccount answers 400 validation_failed with the pointer `/consent_c1/text_version`, and the page reads the text again. An unknown purpose fails parameter validation with 400. + * @summary Read the currently published text of a registration consent. + */ +export const getConsentText = async (purpose: ConsentPurpose, options?: Parameters[1]): Promise => { + + return apiRequest(getGetConsentTextUrl(purpose), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetConsentTextQueryKey = (purpose: ConsentPurpose,) => { + return [ + `/api/v1/identity/consent-texts/${purpose}` + ] as const; + } + + +export const getGetConsentTextQueryOptions = >, TError = ErrorType>(purpose: ConsentPurpose, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetConsentTextQueryKey(purpose); + + + + const queryFn: QueryFunction>> = ({ signal }) => getConsentText(purpose, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, enabled: purpose !== null && purpose !== undefined, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetConsentTextQueryResult = NonNullable>> +export type GetConsentTextQueryError = ErrorType + + +export function useGetConsentText>, TError = ErrorType>( + purpose: ConsentPurpose, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetConsentText>, TError = ErrorType>( + purpose: ConsentPurpose, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetConsentText>, TError = ErrorType>( + purpose: ConsentPurpose, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read the currently published text of a registration consent. + */ + +export function useGetConsentText>, TError = ErrorType>( + purpose: ConsentPurpose, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetConsentTextQueryOptions(purpose,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getRegisterAccountUrl = () => { + + + + + return `/api/v1/identity/registrations` +} + +/** + * Public operation without a session. The client reads the current C1 text with GetConsentText and sends the email, the password, the chosen scenario, and consent C1 with the version of the text the user accepted. + * + * The answer is the same 202 whether the email is new, registered but not verified, or verified, so registration does not enumerate accounts: + * + * - New email: the server creates an unverified account with the scenario and the first onboarding step, records C1 with its text version and text hash, stores only the hash of a one-time verification token, and queues the verification message, all in one transaction. + * - Registered but not verified: the server treats the request as a new registration of that address. In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1 record, advances the registration version, invalidates every earlier verification token, and queues a message with a new token. A pre-registration with someone else's password therefore never survives the address owner's own registration. + * - Verified: nothing changes. The server may queue a rate-limited "you already have an account" notice to the address. + * + * Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration can never confirm the newer credentials. An account that stays unverified is deleted with its consent record and tokens 7 days after its last registration (planned value from configuration). Verification tokens live 24 hours (planned value from configuration). + * + * The response does not depend on the branch in content or timing. Before it looks up the email, the server validates the whole body, including the password bounds after normalization, the password blocklist, and the C1 version, and it computes the Argon2id hash on every branch; a 400 therefore never depends on whether the email exists. Mail is delivered asynchronously from the outbox. + * + * The operation requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email, and the request fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The server never stores the body, the password, or a plain hash of either; the secret keeps the fingerprint from serving as an offline password check. A retry with the same key, email, and body replays the stored 202 without a second message; the same key and email with a different body answers 422 idempotency_key_reused. + * + * It is rate-limited per client and per email and answers 429 with Retry-After when the limit is reached. Like every unsafe request, it requires an allowed Origin and answers 403 csrf_check_failed otherwise. + * @summary Register an account by email with a scenario and consent C1. + */ +export const registerAccount = async (registrationRequest: RegistrationRequest, + headers: RegisterAccountHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getRegisterAccountUrl(), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(registrationRequest) + } +);} + + + + + +export const getRegisterAccountMutationKey = () => ['registerAccount'] as const; + +export const getRegisterAccountMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,RegisterAccountMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,RegisterAccountMutationVariables, TContext> => { + +const mutationKey = getRegisterAccountMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, RegisterAccountMutationVariables> = (props) => { + const {data,headers} = props ?? {}; + + return registerAccount(data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type RegisterAccountMutationResult = NonNullable>> + export type RegisterAccountMutationBody = RegistrationRequest + export type RegisterAccountMutationError = ErrorType + export type RegisterAccountMutationVariables = {data: RegistrationRequest;headers: RegisterAccountHeaders} + + /** + * @summary Register an account by email with a scenario and consent C1. + */ +export const useRegisterAccount = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,RegisterAccountMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + RegisterAccountMutationVariables, + TContext + > => { + return useMutation(getRegisterAccountMutationOptions(options), queryClient); + } + export const getResendEmailVerificationUrl = () => { + + + + + return `/api/v1/identity/email-verification-requests` +} + +/** + * Public operation without a session. The answer is the same 202 for an unknown email, a verified email, and an unverified one, so it does not enumerate accounts. Only for an unverified account does the server issue a new one-time token bound to the current registration version, invalidate every earlier token of that account, and queue the message. Resend never changes the password, the scenario, or the consent record; a user who did not start the pending registration registers again instead, which replaces it. + * + * It is rate-limited per client and per email and answers 429 with Retry-After when the limit is reached. A retry is safe without Idempotency-Key: at worst it replaces the token again within the rate limit. Like every unsafe request, it requires an allowed Origin and answers 403 csrf_check_failed otherwise. + * @summary Request a new email verification link. + */ +export const resendEmailVerification = async (emailVerificationResendRequest: EmailVerificationResendRequest, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getResendEmailVerificationUrl(), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) }, + body: JSON.stringify(emailVerificationResendRequest) + } +);} + + + + + +export const getResendEmailVerificationMutationKey = () => ['resendEmailVerification'] as const; + +export const getResendEmailVerificationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,ResendEmailVerificationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,ResendEmailVerificationMutationVariables, TContext> => { + +const mutationKey = getResendEmailVerificationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, ResendEmailVerificationMutationVariables> = (props) => { + const {data} = props ?? {}; + + return resendEmailVerification(data,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type ResendEmailVerificationMutationResult = NonNullable>> + export type ResendEmailVerificationMutationBody = EmailVerificationResendRequest + export type ResendEmailVerificationMutationError = ErrorType + export type ResendEmailVerificationMutationVariables = {data: EmailVerificationResendRequest} + + /** + * @summary Request a new email verification link. + */ +export const useResendEmailVerification = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,ResendEmailVerificationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + ResendEmailVerificationMutationVariables, + TContext + > => { + return useMutation(getResendEmailVerificationMutationOptions(options), queryClient); + } + export const getConfirmEmailUrl = () => { + + + + + return `/api/v1/identity/email-verifications` +} + +/** + * Public operation without a session. The verification link has the form `/verify-email#token=`: the token travels in the URL fragment, so it never reaches a server log or a Referer header. The page first removes the fragment with `history.replaceState`, then waits for an explicit user action, such as a Confirm button, before it posts the token here. A link scanner that only fetches the page therefore does not consume the token. + * + * The server looks up the token by its hash and, in one transaction, checks that it is unused, not expired, and bound to the current registration version, marks it used, and marks the email verified. Only one of several parallel requests with the same token succeeds. An expired token answers verification_token_expired; an unknown, used, replaced, or superseded token answers verification_token_invalid; neither changes anything. For both, the client offers a new link and sign-in, because the address may already be verified. + * + * A repeated confirmation with an already used token is not an idempotent 200: exactly one request may succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after either outcome is sign-in anyway. + * + * Success does not start a session: the link may be opened on another device or by a mail scanner, and a session must come only from the password. The response returns the scenario and the saved onboarding step so the client can continue after sign-in. The operation is rate-limited and requires an allowed Origin. + * @summary Verify an email with the one-time token from the link. + */ +export const confirmEmail = async (emailVerificationRequest: EmailVerificationRequest, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getConfirmEmailUrl(), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) }, + body: JSON.stringify(emailVerificationRequest) + } +);} + + + + + +export const getConfirmEmailMutationKey = () => ['confirmEmail'] as const; + +export const getConfirmEmailMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,ConfirmEmailMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,ConfirmEmailMutationVariables, TContext> => { + +const mutationKey = getConfirmEmailMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, ConfirmEmailMutationVariables> = (props) => { + const {data} = props ?? {}; + + return confirmEmail(data,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type ConfirmEmailMutationResult = NonNullable>> + export type ConfirmEmailMutationBody = EmailVerificationRequest + export type ConfirmEmailMutationError = ErrorType + export type ConfirmEmailMutationVariables = {data: EmailVerificationRequest} + + /** + * @summary Verify an email with the one-time token from the link. + */ +export const useConfirmEmail = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,ConfirmEmailMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + ConfirmEmailMutationVariables, + TContext + > => { + return useMutation(getConfirmEmailMutationOptions(options), queryClient); + } + export const getLoginUrl = () => { + + + + + return `/api/v1/identity/sessions` +} + +/** + * Public operation that starts a server session. The server verifies the password with Argon2id; for an unknown email it verifies against a fixed dummy hash, so the response time does not reveal whether the account exists. An unknown email and a wrong password both answer 401 invalid_credentials. + * + * Correct credentials for an unverified email answer 403 email_not_verified and create no session. This reveals the verification state only to someone who already knows the password, which proves more than the state itself; the client offers to resend the link. + * + * On success the server revokes the session that the request carried, if any, creates a new random session in PostgreSQL with a new identifier and a new CSRF token, sets the HttpOnly session cookie, and returns the account and the CSRF token. The new session follows the idle and absolute timeouts of the sessionCookie scheme. The client keeps the token in memory and sends it in X-CSRF-Token with every mutating request that requires a session. + * + * Login is rate-limited per client and per email and answers 429 with Retry-After. Like every unsafe request, it requires an allowed Origin, which protects against login CSRF, and answers 403 csrf_check_failed otherwise. + * @summary Sign in with email and password and start a session. + */ +export const login = async (loginRequest: LoginRequest, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getLoginUrl(), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) }, + body: JSON.stringify(loginRequest) + } +);} + + + + + +export const getLoginMutationKey = () => ['login'] as const; + +export const getLoginMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,LoginMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,LoginMutationVariables, TContext> => { + +const mutationKey = getLoginMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, LoginMutationVariables> = (props) => { + const {data} = props ?? {}; + + return login(data,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type LoginMutationResult = NonNullable>> + export type LoginMutationBody = LoginRequest + export type LoginMutationError = ErrorType + export type LoginMutationVariables = {data: LoginRequest} + + /** + * @summary Sign in with email and password and start a session. + */ +export const useLogin = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,LoginMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + LoginMutationVariables, + TContext + > => { + return useMutation(getLoginMutationOptions(options), queryClient); + } + export const getGetCurrentSessionUrl = () => { + + + + + return `/api/v1/identity/sessions/current` +} + +/** + * Requires the session cookie. Returns the account and the CSRF token of the current session, so the client can restore the token after a page reload or after 403 csrf_check_failed. A missing, unknown, expired, or revoked session answers 401 unauthenticated. Cross-origin pages cannot read the token, because the API sends no Access-Control-Allow-Origin header. + * @summary Read the current session and its CSRF token. + */ +export const getCurrentSession = async ( options?: Parameters[1]): Promise => { + + return apiRequest(getGetCurrentSessionUrl(), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetCurrentSessionQueryKey = () => { + return [ + `/api/v1/identity/sessions/current` + ] as const; + } + + +export const getGetCurrentSessionQueryOptions = >, TError = ErrorType>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetCurrentSessionQueryKey(); + + + + const queryFn: QueryFunction>> = ({ signal }) => getCurrentSession({ signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetCurrentSessionQueryResult = NonNullable>> +export type GetCurrentSessionQueryError = ErrorType + + +export function useGetCurrentSession>, TError = ErrorType>( + options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetCurrentSession>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetCurrentSession>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read the current session and its CSRF token. + */ + +export function useGetCurrentSession>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetCurrentSessionQueryOptions(options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getLogoutUrl = () => { + + + + + return `/api/v1/identity/sessions/current` +} + +/** + * Requires the session cookie and the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The server revokes the session in PostgreSQL, so the cookie value stops working even if a copy remains, and clears the cookie. A missing, expired, or revoked session answers 401 unauthenticated and also clears the cookie, so a stale cookie does not stay in the browser; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed and keeps the session and the cookie. The client clears its private query cache after the response. + * @summary Sign out and revoke the current session. + */ +export const logout = async ( options?: Parameters[1]): Promise => { + + return apiRequest(getLogoutUrl(), + { + ...options, + method: 'DELETE' + + + } +);} + + + + + +export const getLogoutMutationKey = () => ['logout'] as const; + +export const getLogoutMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,void, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,void, TContext> => { + +const mutationKey = getLogoutMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, void> = () => { + + + return logout(requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type LogoutMutationResult = NonNullable>> + + export type LogoutMutationError = ErrorType + + + /** + * @summary Sign out and revoke the current session. + */ +export const useLogout = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,void, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + void, + TContext + > => { + return useMutation(getLogoutMutationOptions(options), queryClient); + } + export const getGetCurrentAccountUrl = () => { + + + + + return `/api/v1/identity/me` +} + +/** + * Requires the session cookie. The account comes from the session, never from a request parameter. The client uses `scenario` and `onboarding_step` to return the user to the unfinished onboarding step. A missing, unknown, expired, or revoked session answers 401 unauthenticated. An unverified account never has a session, because login answers 403 email_not_verified for it, so this operation also answers 401 for such an account. + * @summary Read the account of the current session. + */ +export const getCurrentAccount = async ( options?: Parameters[1]): Promise => { + + return apiRequest(getGetCurrentAccountUrl(), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetCurrentAccountQueryKey = () => { + return [ + `/api/v1/identity/me` + ] as const; + } + + +export const getGetCurrentAccountQueryOptions = >, TError = ErrorType>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetCurrentAccountQueryKey(); + + + + const queryFn: QueryFunction>> = ({ signal }) => getCurrentAccount({ signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetCurrentAccountQueryResult = NonNullable>> +export type GetCurrentAccountQueryError = ErrorType + + +export function useGetCurrentAccount>, TError = ErrorType>( + options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetCurrentAccount>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetCurrentAccount>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read the account of the current session. + */ + +export function useGetCurrentAccount>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetCurrentAccountQueryOptions(options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + diff --git a/frontend/src/shared/api/endpoints/index.msw.ts b/frontend/src/shared/api/endpoints/index.msw.ts index d506d69..a7e742b 100644 --- a/frontend/src/shared/api/endpoints/index.msw.ts +++ b/frontend/src/shared/api/endpoints/index.msw.ts @@ -1 +1,2 @@ export { getHealthMock } from './health/health.msw' +export { getIdentityMock } from './identity/identity.msw' diff --git a/frontend/src/shared/api/endpoints/index.ts b/frontend/src/shared/api/endpoints/index.ts index d2eafb0..3641307 100644 --- a/frontend/src/shared/api/endpoints/index.ts +++ b/frontend/src/shared/api/endpoints/index.ts @@ -1 +1,2 @@ export * from './health/health'; +export * from './identity/identity'; diff --git a/frontend/src/shared/api/schemas/health/index.ts b/frontend/src/shared/api/schemas/health/index.ts index 39932a5..ae7e418 100644 --- a/frontend/src/shared/api/schemas/health/index.ts +++ b/frontend/src/shared/api/schemas/health/index.ts @@ -6,7 +6,3 @@ */ export * from './healthResponse.zod'; -export * from './problem.zod'; -export * from './problemCode.zod'; -export * from './problemFieldError.zod'; -export * from './problemFieldLocation.zod'; diff --git a/frontend/src/shared/api/schemas/health/problemCode.zod.ts b/frontend/src/shared/api/schemas/health/problemCode.zod.ts deleted file mode 100644 index 90d890b..0000000 --- a/frontend/src/shared/api/schemas/health/problemCode.zod.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Generated by orval 🍺 - * Do not edit manually. - * Lincodex API - * OpenAPI spec version: 0.1.0 - */ -import * as zod from 'zod'; - -export const ProblemCode = zod.enum(['validation_failed', 'unauthenticated', 'forbidden', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.') - -export type ProblemCode = zod.input; -export type ProblemCodeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/account.zod.ts b/frontend/src/shared/api/schemas/identity/account.zod.ts new file mode 100644 index 0000000..53fa7b1 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/account.zod.ts @@ -0,0 +1,23 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const accountEmailMin = 3; +export const accountEmailMax = 254; + + +export const Account = zod.object({ + "id": zod.uuid().describe('Account identifier.'), + "email": zod.email().min(accountEmailMin).max(accountEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'), + "email_verified": zod.boolean().describe('Whether the address is verified. A session exists only for a verified account, so this is true in every current response.'), + "scenario": zod.enum(['candidate', 'employer']).describe('Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, `employer` represents a company that searches for candidates. The scenario selects the onboarding steps.'), + "onboarding_step": zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: choice of the expected grade and the assessment.\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.'), + "created_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('Current account view. It never contains password hashes, token hashes, session identifiers, or other storage secrets.') + +export type Account = zod.input; +export type AccountOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/accountScenario.zod.ts b/frontend/src/shared/api/schemas/identity/accountScenario.zod.ts new file mode 100644 index 0000000..5d9ce15 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/accountScenario.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const AccountScenario = zod.enum(['candidate', 'employer']).describe('Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, `employer` represents a company that searches for candidates. The scenario selects the onboarding steps.') + +export type AccountScenario = zod.input; +export type AccountScenarioOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/confirmEmailBody.zod.ts b/frontend/src/shared/api/schemas/identity/confirmEmailBody.zod.ts new file mode 100644 index 0000000..c2a3016 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/confirmEmailBody.zod.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const confirmEmailBodyTokenMin = 32; +export const confirmEmailBodyTokenMax = 128; + + +export const confirmEmailBodyTokenRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const ConfirmEmailBody = zod.object({ + "token": zod.string().min(confirmEmailBodyTokenMin).max(confirmEmailBodyTokenMax).regex(confirmEmailBodyTokenRegExp).describe('One-time raw token copied from the verification link. It is request input only: the server stores only its hash and never returns a token.') +}).describe('Token from the email verification link.') + +export type ConfirmEmailBody = zod.input; +export type ConfirmEmailBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/consentPurpose.zod.ts b/frontend/src/shared/api/schemas/identity/consentPurpose.zod.ts new file mode 100644 index 0000000..6fa8c04 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/consentPurpose.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const ConsentPurpose = zod.enum(['c1']).describe('Consent whose text the client may read before an account exists. Only the consents given at registration are listed: `c1` is the consent to the processing of personal data.') + +export type ConsentPurpose = zod.input; +export type ConsentPurposeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/consentText.zod.ts b/frontend/src/shared/api/schemas/identity/consentText.zod.ts new file mode 100644 index 0000000..191179d --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/consentText.zod.ts @@ -0,0 +1,24 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const consentTextTextVersionMax = 64; + + +export const consentTextTextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); +export const consentTextTextMax = 100000; + + +export const ConsentText = zod.object({ + "purpose": zod.enum(['c1']).describe('Consent whose text the client may read before an account exists. Only the consents given at registration are listed: `c1` is the consent to the processing of personal data.'), + "text_version": zod.string().min(1).max(consentTextTextVersionMax).regex(consentTextTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), + "text": zod.string().min(1).max(consentTextTextMax).describe('Full consent text in plain UTF-8; paragraphs are separated by an empty line. The client shows it as text, never as HTML.'), + "published_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('Currently published consent text. The server stores an acceptance with `text_version` and the hash of exactly this text.') + +export type ConsentText = zod.input; +export type ConsentTextOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/consentTextVersion.zod.ts b/frontend/src/shared/api/schemas/identity/consentTextVersion.zod.ts new file mode 100644 index 0000000..66dfcb6 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/consentTextVersion.zod.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const ConsentTextVersionMax = 64; + + +export const ConsentTextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); + +export const ConsentTextVersion = zod.string().min(1).max(ConsentTextVersionMax).regex(ConsentTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.') + +export type ConsentTextVersion = zod.input; +export type ConsentTextVersionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/csrfToken.zod.ts b/frontend/src/shared/api/schemas/identity/csrfToken.zod.ts new file mode 100644 index 0000000..029370e --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/csrfToken.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const CsrfTokenMin = 32; +export const CsrfTokenMax = 128; + + +export const CsrfTokenRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const CsrfToken = zod.string().min(CsrfTokenMin).max(CsrfTokenMax).regex(CsrfTokenRegExp).describe('CSRF token bound to the current session. The client keeps it in memory only and sends it in the X-CSRF-Token header of every mutating request that requires a session. It changes when a new session starts.') + +export type CsrfToken = zod.input; +export type CsrfTokenOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/emailAddress.zod.ts b/frontend/src/shared/api/schemas/identity/emailAddress.zod.ts new file mode 100644 index 0000000..d212d05 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/emailAddress.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const EmailAddressMin = 3; +export const EmailAddressMax = 254; + + +export const EmailAddress = zod.email().min(EmailAddressMin).max(EmailAddressMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.') + +export type EmailAddress = zod.input; +export type EmailAddressOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/emailVerificationRequest.zod.ts b/frontend/src/shared/api/schemas/identity/emailVerificationRequest.zod.ts new file mode 100644 index 0000000..5afae33 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/emailVerificationRequest.zod.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const emailVerificationRequestTokenMin = 32; +export const emailVerificationRequestTokenMax = 128; + + +export const emailVerificationRequestTokenRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const EmailVerificationRequest = zod.object({ + "token": zod.string().min(emailVerificationRequestTokenMin).max(emailVerificationRequestTokenMax).regex(emailVerificationRequestTokenRegExp).describe('One-time raw token copied from the verification link. It is request input only: the server stores only its hash and never returns a token.') +}).describe('Token from the email verification link.') + +export type EmailVerificationRequest = zod.input; +export type EmailVerificationRequestOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/emailVerificationResendRequest.zod.ts b/frontend/src/shared/api/schemas/identity/emailVerificationResendRequest.zod.ts new file mode 100644 index 0000000..ae24164 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/emailVerificationResendRequest.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const emailVerificationResendRequestEmailMin = 3; +export const emailVerificationResendRequestEmailMax = 254; + + +export const EmailVerificationResendRequest = zod.object({ + "email": zod.email().min(emailVerificationResendRequestEmailMin).max(emailVerificationResendRequestEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.') +}).describe('Address that should receive a new verification link.') + +export type EmailVerificationResendRequest = zod.input; +export type EmailVerificationResendRequestOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/emailVerificationResult.zod.ts b/frontend/src/shared/api/schemas/identity/emailVerificationResult.zod.ts new file mode 100644 index 0000000..6486d3a --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/emailVerificationResult.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const EmailVerificationResult = zod.object({ + "email_verified": zod.literal(true).describe('Always true in a successful response.'), + "scenario": zod.enum(['candidate', 'employer']).describe('Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, `employer` represents a company that searches for candidates. The scenario selects the onboarding steps.'), + "onboarding_step": zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: choice of the expected grade and the assessment.\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.') +}).describe('Result of a successful email verification. It does not start a session; the user signs in next and continues from `onboarding_step`.') + +export type EmailVerificationResult = zod.input; +export type EmailVerificationResultOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/identityRequestAccepted.zod.ts b/frontend/src/shared/api/schemas/identity/identityRequestAccepted.zod.ts new file mode 100644 index 0000000..18b7f49 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/identityRequestAccepted.zod.ts @@ -0,0 +1,14 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const IdentityRequestAccepted = zod.object({ + "status": zod.enum(['accepted']) +}).describe('Neutral acknowledgement. Its content is identical whether or not the address belongs to an account or is already verified, so the response does not enumerate accounts. The client tells the user to check the mailbox.') + +export type IdentityRequestAccepted = zod.input; +export type IdentityRequestAcceptedOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/index.ts b/frontend/src/shared/api/schemas/identity/index.ts new file mode 100644 index 0000000..650246d --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/index.ts @@ -0,0 +1,32 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ + +export * from './account.zod'; +export * from './accountScenario.zod'; +export * from './confirmEmailBody.zod'; +export * from './consentPurpose.zod'; +export * from './consentText.zod'; +export * from './consentTextVersion.zod'; +export * from './csrfToken.zod'; +export * from './emailAddress.zod'; +export * from './emailVerificationRequest.zod'; +export * from './emailVerificationResendRequest.zod'; +export * from './emailVerificationResult.zod'; +export * from './identityRequestAccepted.zod'; +export * from './loginBody.zod'; +export * from './loginPassword.zod'; +export * from './loginRequest.zod'; +export * from './newPassword.zod'; +export * from './onboardingStep.zod'; +export * from './personalDataConsentAcceptance.zod'; +export * from './registerAccountBody.zod'; +export * from './registerAccountHeaders.zod'; +export * from './registrationRequest.zod'; +export * from './resendEmailVerificationBody.zod'; +export * from './session.zod'; +export * from './timestamp.zod'; +export * from './verificationToken.zod'; diff --git a/frontend/src/shared/api/schemas/identity/loginBody.zod.ts b/frontend/src/shared/api/schemas/identity/loginBody.zod.ts new file mode 100644 index 0000000..fd537d8 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/loginBody.zod.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const loginBodyEmailMin = 3; +export const loginBodyEmailMax = 254; + +export const loginBodyPasswordMax = 128; + + +export const LoginBody = zod.object({ + "email": zod.email().min(loginBodyEmailMin).max(loginBodyEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'), + "password": zod.string().min(1).max(loginBodyPasswordMax).describe('Password entered at login. The server applies the same NFKC normalization as at registration before it verifies the hash. Only the hashing bound applies, so a later change of the registration policy does not lock out existing accounts and a login error does not reveal the policy. The value is never returned, logged, or echoed in a problem.') +}).describe('Email and password of the account.') + +export type LoginBody = zod.input; +export type LoginBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/loginPassword.zod.ts b/frontend/src/shared/api/schemas/identity/loginPassword.zod.ts new file mode 100644 index 0000000..2b029cb --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/loginPassword.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const LoginPasswordMax = 128; + + +export const LoginPassword = zod.string().min(1).max(LoginPasswordMax).describe('Password entered at login. The server applies the same NFKC normalization as at registration before it verifies the hash. Only the hashing bound applies, so a later change of the registration policy does not lock out existing accounts and a login error does not reveal the policy. The value is never returned, logged, or echoed in a problem.') + +export type LoginPassword = zod.input; +export type LoginPasswordOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/loginRequest.zod.ts b/frontend/src/shared/api/schemas/identity/loginRequest.zod.ts new file mode 100644 index 0000000..5f21485 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/loginRequest.zod.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const loginRequestEmailMin = 3; +export const loginRequestEmailMax = 254; + +export const loginRequestPasswordMax = 128; + + +export const LoginRequest = zod.object({ + "email": zod.email().min(loginRequestEmailMin).max(loginRequestEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'), + "password": zod.string().min(1).max(loginRequestPasswordMax).describe('Password entered at login. The server applies the same NFKC normalization as at registration before it verifies the hash. Only the hashing bound applies, so a later change of the registration policy does not lock out existing accounts and a login error does not reveal the policy. The value is never returned, logged, or echoed in a problem.') +}).describe('Email and password of the account.') + +export type LoginRequest = zod.input; +export type LoginRequestOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/newPassword.zod.ts b/frontend/src/shared/api/schemas/identity/newPassword.zod.ts new file mode 100644 index 0000000..e584eeb --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/newPassword.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const NewPasswordMin = 15; +export const NewPasswordMax = 128; + + +export const NewPassword = zod.string().min(NewPasswordMin).max(NewPasswordMax).describe('Password chosen at registration. The server normalizes it to Unicode NFKC, as NIST SP 800-63B-4 recommends, and then requires 15 to 128 Unicode code points; a value that the schema accepts can still fail this check after normalization. The 15-character minimum follows NIST SP 800-63B-4 for a password used as the only authentication factor; there are no composition rules. The upper bound limits the cost of password hashing. Generated client validators count UTF-16 code units, so a password with characters outside the Basic Multilingual Plane can pass the client check and fail on the server; a later client check should count code points. A password on the server blocklist of common or breached passwords answers 400 validation_failed with the pointer `/password`. The value is never returned, logged, or echoed in a problem.') + +export type NewPassword = zod.input; +export type NewPasswordOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/onboardingStep.zod.ts b/frontend/src/shared/api/schemas/identity/onboardingStep.zod.ts new file mode 100644 index 0000000..fb6a06c --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/onboardingStep.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const OnboardingStep = zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: choice of the expected grade and the assessment.\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.') + +export type OnboardingStep = zod.input; +export type OnboardingStepOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/personalDataConsentAcceptance.zod.ts b/frontend/src/shared/api/schemas/identity/personalDataConsentAcceptance.zod.ts new file mode 100644 index 0000000..67b277c --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/personalDataConsentAcceptance.zod.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const personalDataConsentAcceptanceTextVersionMax = 64; + + +export const personalDataConsentAcceptanceTextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); + +export const PersonalDataConsentAcceptance = zod.object({ + "text_version": zod.string().min(1).max(personalDataConsentAcceptanceTextVersionMax).regex(personalDataConsentAcceptanceTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), + "accepted": zod.literal(true).describe('Explicit acceptance. Only true is valid.') +}).describe('Consent C1 to the processing of personal data, given at registration. The client reads the current text and its version with GetConsentText(c1) and sends that version here. A version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c1/text_version`; the client then reads the text again and asks the user to accept the new version. Unknown fields are rejected, so registration cannot carry any other consent; in particular, C4 is never part of registration.') + +export type PersonalDataConsentAcceptance = zod.input; +export type PersonalDataConsentAcceptanceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/registerAccountBody.zod.ts b/frontend/src/shared/api/schemas/identity/registerAccountBody.zod.ts new file mode 100644 index 0000000..4d720d1 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/registerAccountBody.zod.ts @@ -0,0 +1,31 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const registerAccountBodyEmailMin = 3; +export const registerAccountBodyEmailMax = 254; + +export const registerAccountBodyPasswordMin = 15; +export const registerAccountBodyPasswordMax = 128; + +export const registerAccountBodyConsentC1TextVersionMax = 64; + + +export const registerAccountBodyConsentC1TextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); + +export const RegisterAccountBody = zod.object({ + "email": zod.email().min(registerAccountBodyEmailMin).max(registerAccountBodyEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'), + "password": zod.string().min(registerAccountBodyPasswordMin).max(registerAccountBodyPasswordMax).describe('Password chosen at registration. The server normalizes it to Unicode NFKC, as NIST SP 800-63B-4 recommends, and then requires 15 to 128 Unicode code points; a value that the schema accepts can still fail this check after normalization. The 15-character minimum follows NIST SP 800-63B-4 for a password used as the only authentication factor; there are no composition rules. The upper bound limits the cost of password hashing. Generated client validators count UTF-16 code units, so a password with characters outside the Basic Multilingual Plane can pass the client check and fail on the server; a later client check should count code points. A password on the server blocklist of common or breached passwords answers 400 validation_failed with the pointer `/password`. The value is never returned, logged, or echoed in a problem.'), + "scenario": zod.enum(['candidate', 'employer']).describe('Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, `employer` represents a company that searches for candidates. The scenario selects the onboarding steps.'), + "consent_c1": zod.object({ + "text_version": zod.string().min(1).max(registerAccountBodyConsentC1TextVersionMax).regex(registerAccountBodyConsentC1TextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), + "accepted": zod.literal(true).describe('Explicit acceptance. Only true is valid.') +}).describe('Consent C1 to the processing of personal data, given at registration. The client reads the current text and its version with GetConsentText(c1) and sends that version here. A version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c1/text_version`; the client then reads the text again and asks the user to accept the new version. Unknown fields are rejected, so registration cannot carry any other consent; in particular, C4 is never part of registration.') +}).describe('New account with its scenario and consent C1.') + +export type RegisterAccountBody = zod.input; +export type RegisterAccountBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/registerAccountHeaders.zod.ts b/frontend/src/shared/api/schemas/identity/registerAccountHeaders.zod.ts new file mode 100644 index 0000000..2127d24 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/registerAccountHeaders.zod.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const registerAccountHeadersIdempotencyKeyMax = 255; + + +export const registerAccountHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const RegisterAccountHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(registerAccountHeadersIdempotencyKeyMax).regex(registerAccountHeadersIdempotencyKeyRegExp) +}) + +export type RegisterAccountHeaders = zod.input; +export type RegisterAccountHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/registrationRequest.zod.ts b/frontend/src/shared/api/schemas/identity/registrationRequest.zod.ts new file mode 100644 index 0000000..4de03f6 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/registrationRequest.zod.ts @@ -0,0 +1,31 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const registrationRequestEmailMin = 3; +export const registrationRequestEmailMax = 254; + +export const registrationRequestPasswordMin = 15; +export const registrationRequestPasswordMax = 128; + +export const registrationRequestConsentC1TextVersionMax = 64; + + +export const registrationRequestConsentC1TextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$'); + +export const RegistrationRequest = zod.object({ + "email": zod.email().min(registrationRequestEmailMin).max(registrationRequestEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'), + "password": zod.string().min(registrationRequestPasswordMin).max(registrationRequestPasswordMax).describe('Password chosen at registration. The server normalizes it to Unicode NFKC, as NIST SP 800-63B-4 recommends, and then requires 15 to 128 Unicode code points; a value that the schema accepts can still fail this check after normalization. The 15-character minimum follows NIST SP 800-63B-4 for a password used as the only authentication factor; there are no composition rules. The upper bound limits the cost of password hashing. Generated client validators count UTF-16 code units, so a password with characters outside the Basic Multilingual Plane can pass the client check and fail on the server; a later client check should count code points. A password on the server blocklist of common or breached passwords answers 400 validation_failed with the pointer `/password`. The value is never returned, logged, or echoed in a problem.'), + "scenario": zod.enum(['candidate', 'employer']).describe('Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, `employer` represents a company that searches for candidates. The scenario selects the onboarding steps.'), + "consent_c1": zod.object({ + "text_version": zod.string().min(1).max(registrationRequestConsentC1TextVersionMax).regex(registrationRequestConsentC1TextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'), + "accepted": zod.literal(true).describe('Explicit acceptance. Only true is valid.') +}).describe('Consent C1 to the processing of personal data, given at registration. The client reads the current text and its version with GetConsentText(c1) and sends that version here. A version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c1/text_version`; the client then reads the text again and asks the user to accept the new version. Unknown fields are rejected, so registration cannot carry any other consent; in particular, C4 is never part of registration.') +}).describe('New account with its scenario and consent C1.') + +export type RegistrationRequest = zod.input; +export type RegistrationRequestOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/resendEmailVerificationBody.zod.ts b/frontend/src/shared/api/schemas/identity/resendEmailVerificationBody.zod.ts new file mode 100644 index 0000000..49dcf4b --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/resendEmailVerificationBody.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const resendEmailVerificationBodyEmailMin = 3; +export const resendEmailVerificationBodyEmailMax = 254; + + +export const ResendEmailVerificationBody = zod.object({ + "email": zod.email().min(resendEmailVerificationBodyEmailMin).max(resendEmailVerificationBodyEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.') +}).describe('Address that should receive a new verification link.') + +export type ResendEmailVerificationBody = zod.input; +export type ResendEmailVerificationBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/session.zod.ts b/frontend/src/shared/api/schemas/identity/session.zod.ts new file mode 100644 index 0000000..9381143 --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/session.zod.ts @@ -0,0 +1,31 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const sessionAccountEmailMin = 3; +export const sessionAccountEmailMax = 254; + +export const sessionCsrfTokenMin = 32; +export const sessionCsrfTokenMax = 128; + + +export const sessionCsrfTokenRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const Session = zod.object({ + "account": zod.object({ + "id": zod.uuid().describe('Account identifier.'), + "email": zod.email().min(sessionAccountEmailMin).max(sessionAccountEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'), + "email_verified": zod.boolean().describe('Whether the address is verified. A session exists only for a verified account, so this is true in every current response.'), + "scenario": zod.enum(['candidate', 'employer']).describe('Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, `employer` represents a company that searches for candidates. The scenario selects the onboarding steps.'), + "onboarding_step": zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: choice of the expected grade and the assessment.\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.'), + "created_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('Current account view. It never contains password hashes, token hashes, session identifiers, or other storage secrets.'), + "csrf_token": zod.string().min(sessionCsrfTokenMin).max(sessionCsrfTokenMax).regex(sessionCsrfTokenRegExp).describe('CSRF token bound to the current session. The client keeps it in memory only and sends it in the X-CSRF-Token header of every mutating request that requires a session. It changes when a new session starts.') +}).describe('Current session as the client may see it: the account and the CSRF token. The session identifier itself travels only in the HttpOnly session cookie and never appears in a body.') + +export type Session = zod.input; +export type SessionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/timestamp.zod.ts b/frontend/src/shared/api/schemas/identity/timestamp.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/timestamp.zod.ts rename to frontend/src/shared/api/schemas/identity/timestamp.zod.ts diff --git a/frontend/src/shared/api/schemas/identity/verificationToken.zod.ts b/frontend/src/shared/api/schemas/identity/verificationToken.zod.ts new file mode 100644 index 0000000..67594ce --- /dev/null +++ b/frontend/src/shared/api/schemas/identity/verificationToken.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const VerificationTokenMin = 32; +export const VerificationTokenMax = 128; + + +export const VerificationTokenRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const VerificationToken = zod.string().min(VerificationTokenMin).max(VerificationTokenMax).regex(VerificationTokenRegExp).describe('One-time raw token copied from the verification link. It is request input only: the server stores only its hash and never returns a token.') + +export type VerificationToken = zod.input; +export type VerificationTokenOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/index.ts b/frontend/src/shared/api/schemas/index.ts index 6d1eb71..491f0c8 100644 --- a/frontend/src/shared/api/schemas/index.ts +++ b/frontend/src/shared/api/schemas/index.ts @@ -6,5 +6,9 @@ */ export * from './pageInfo.zod'; -export * from './timestamp.zod'; +export * from './problem.zod'; +export * from './problemCode.zod'; +export * from './problemFieldError.zod'; +export * from './problemFieldLocation.zod'; export * from './health'; +export * from './identity'; diff --git a/frontend/src/shared/api/schemas/health/problem.zod.ts b/frontend/src/shared/api/schemas/problem.zod.ts similarity index 58% rename from frontend/src/shared/api/schemas/health/problem.zod.ts rename to frontend/src/shared/api/schemas/problem.zod.ts index 9e09c18..b35086d 100644 --- a/frontend/src/shared/api/schemas/health/problem.zod.ts +++ b/frontend/src/shared/api/schemas/problem.zod.ts @@ -38,7 +38,7 @@ export const Problem = zod.object({ "type": zod.string().max(problemTypeMax).describe('URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference.'), "title": zod.string().min(1).max(problemTitleMax).describe('Short, fixed English summary of the problem type. It does not change between occurrences.'), "status": zod.int().min(problemStatusMin).max(problemStatusMax).describe('HTTP status code generated by the origin server.'), - "code": zod.enum(['validation_failed', 'unauthenticated', 'forbidden', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.'), + "code": zod.enum(['validation_failed', 'verification_token_invalid', 'verification_token_expired', 'unauthenticated', 'invalid_credentials', 'forbidden', 'email_not_verified', 'csrf_check_failed', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- verification_token_invalid (400): the email verification token is unknown, already used, or replaced by a newer one; request a new link or sign in.\n- verification_token_expired (400): the email verification token is past its lifetime; request a new link.\n- unauthenticated (401): no valid session or credentials.\n- invalid_credentials (401): the email and password do not match an account; an unknown email and a wrong password are not distinguished.\n- forbidden (403): the caller is authenticated but not allowed.\n- email_not_verified (403): the credentials are correct but the email is not verified yet.\n- csrf_check_failed (403): the request failed cross-site request protection: a missing or wrong X-CSRF-Token or a disallowed Origin.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.'), "detail": zod.string().max(problemDetailMax).exactOptional().describe('Safe English explanation of this occurrence. It never contains internal error text or request values.'), "instance": zod.string().max(problemInstanceMax).exactOptional().describe('URI reference that identifies this occurrence, when one exists.'), "trace_id": zod.string().min(1).max(problemTraceIdMax).regex(problemTraceIdRegExp).exactOptional().describe('Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; it is not a secret.'), diff --git a/frontend/src/shared/api/schemas/problemCode.zod.ts b/frontend/src/shared/api/schemas/problemCode.zod.ts new file mode 100644 index 0000000..a3f6107 --- /dev/null +++ b/frontend/src/shared/api/schemas/problemCode.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const ProblemCode = zod.enum(['validation_failed', 'verification_token_invalid', 'verification_token_expired', 'unauthenticated', 'invalid_credentials', 'forbidden', 'email_not_verified', 'csrf_check_failed', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- verification_token_invalid (400): the email verification token is unknown, already used, or replaced by a newer one; request a new link or sign in.\n- verification_token_expired (400): the email verification token is past its lifetime; request a new link.\n- unauthenticated (401): no valid session or credentials.\n- invalid_credentials (401): the email and password do not match an account; an unknown email and a wrong password are not distinguished.\n- forbidden (403): the caller is authenticated but not allowed.\n- email_not_verified (403): the credentials are correct but the email is not verified yet.\n- csrf_check_failed (403): the request failed cross-site request protection: a missing or wrong X-CSRF-Token or a disallowed Origin.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.') + +export type ProblemCode = zod.input; +export type ProblemCodeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/health/problemFieldError.zod.ts b/frontend/src/shared/api/schemas/problemFieldError.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/health/problemFieldError.zod.ts rename to frontend/src/shared/api/schemas/problemFieldError.zod.ts diff --git a/frontend/src/shared/api/schemas/health/problemFieldLocation.zod.ts b/frontend/src/shared/api/schemas/problemFieldLocation.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/health/problemFieldLocation.zod.ts rename to frontend/src/shared/api/schemas/problemFieldLocation.zod.ts diff --git a/ml/src/lincodex_ml/api/models.py b/ml/src/lincodex_ml/api/models.py index c8f7590..d66aea1 100644 --- a/ml/src/lincodex_ml/api/models.py +++ b/ml/src/lincodex_ml/api/models.py @@ -10,8 +10,13 @@ class ProblemCode( RootModel[ Literal[ "validation_failed", + "verification_token_invalid", + "verification_token_expired", "unauthenticated", + "invalid_credentials", "forbidden", + "email_not_verified", + "csrf_check_failed", "not_found", "method_not_allowed", "idempotency_in_progress", @@ -30,8 +35,13 @@ class ProblemCode( root: Annotated[ Literal[ "validation_failed", + "verification_token_invalid", + "verification_token_expired", "unauthenticated", + "invalid_credentials", "forbidden", + "email_not_verified", + "csrf_check_failed", "not_found", "method_not_allowed", "idempotency_in_progress", @@ -46,7 +56,7 @@ class ProblemCode( "not_implemented", ], Field( - description="Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet." + description="Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.\n\nThe enum keeps the public API codes so both contracts share one Problem shape. The identity codes verification_token_invalid, verification_token_expired, invalid_credentials, email_not_verified, and csrf_check_failed belong to the public API; the ML service never returns them." ), ] From 15e2e505618fa33488179596e2ce4a857791b9a9 Mon Sep 17 00:00:00 2001 From: shira Date: Mon, 5 Oct 2026 23:32:43 +0300 Subject: [PATCH 006/143] feat(backend): add transactional outbox and embedded goose migrations --- backend/Makefile | 12 +- backend/cmd/migrate/main.go | 116 ++++ backend/config/config.go | 72 +- backend/config/config_test.go | 31 +- backend/db/migrations.go | 25 + backend/db/migrations/.gitkeep | 1 - .../migrations/00001_create_outbox_events.sql | 54 ++ backend/db/migrations_test.go | 44 ++ backend/db/queries/outbox.sql | 18 + backend/go.mod | 4 +- backend/integration_test/bootstrap_test.go | 1 + backend/integration_test/outbox_test.go | 654 ++++++++++++++++++ .../integration_test/postgres_helpers_test.go | 137 ++++ .../postgres_migrations_test.go | 141 ++++ .../adapter/secondary/postgres/health.go | 8 +- .../secondary/postgres/integration_seam.go | 20 + .../adapter/secondary/postgres/migrator.go | 156 +++++ .../secondary/postgres/migrator_test.go | 94 +++ .../adapter/secondary/postgres/outbox.go | 63 ++ .../adapter/secondary/postgres/outbox_test.go | 45 ++ .../adapter/secondary/postgres/pool.go | 42 ++ .../adapter/secondary/postgres/sqlc/models.go | 17 + .../secondary/postgres/sqlc/outbox.sql.go | 55 ++ .../secondary/postgres/sqlc/querier.go | 1 + .../adapter/secondary/postgres/transactor.go | 104 +++ backend/internal/bootstrap/app.go | 3 + backend/internal/bootstrap/app_test.go | 35 + backend/internal/bootstrap/migrate.go | 57 ++ backend/internal/domain/.gitkeep | 0 backend/internal/domain/domain_event.go | 183 +++++ backend/internal/domain/domain_event_test.go | 138 ++++ backend/internal/port/outbound/transaction.go | 57 ++ docs/en/ARCHITECTURE.md | 45 +- docs/en/DEPLOY.md | 2 + docs/en/DEVELOPMENT.md | 24 +- docs/en/TESTING.md | 4 +- docs/ru/ARCHITECTURE.md | 45 +- docs/ru/DEPLOY.md | 2 + docs/ru/DEVELOPMENT.md | 24 +- docs/ru/TESTING.md | 4 +- 40 files changed, 2471 insertions(+), 67 deletions(-) create mode 100644 backend/cmd/migrate/main.go create mode 100644 backend/db/migrations.go delete mode 100644 backend/db/migrations/.gitkeep create mode 100644 backend/db/migrations/00001_create_outbox_events.sql create mode 100644 backend/db/migrations_test.go create mode 100644 backend/db/queries/outbox.sql create mode 100644 backend/integration_test/outbox_test.go create mode 100644 backend/integration_test/postgres_helpers_test.go create mode 100644 backend/integration_test/postgres_migrations_test.go create mode 100644 backend/internal/adapter/secondary/postgres/integration_seam.go create mode 100644 backend/internal/adapter/secondary/postgres/migrator.go create mode 100644 backend/internal/adapter/secondary/postgres/migrator_test.go create mode 100644 backend/internal/adapter/secondary/postgres/outbox.go create mode 100644 backend/internal/adapter/secondary/postgres/outbox_test.go create mode 100644 backend/internal/adapter/secondary/postgres/pool.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/outbox.sql.go create mode 100644 backend/internal/adapter/secondary/postgres/transactor.go create mode 100644 backend/internal/bootstrap/migrate.go delete mode 100644 backend/internal/domain/.gitkeep create mode 100644 backend/internal/domain/domain_event.go create mode 100644 backend/internal/domain/domain_event_test.go create mode 100644 backend/internal/port/outbound/transaction.go diff --git a/backend/Makefile b/backend/Makefile index 21e55ff..9dd3e81 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -23,6 +23,16 @@ build: ## Build the application binary run: ## Run the application with the current environment $(GO) run ./cmd/app +.PHONY: migrate-status migrate-up migrate-down-one +migrate-status: ## Show embedded migration status for the database in DATABASE_URL + $(GO) run ./cmd/migrate status + +migrate-up: ## Apply pending embedded migrations to the database in DATABASE_URL + $(GO) run ./cmd/migrate up + +migrate-down-one: ## Roll back the latest applied migration in the database in DATABASE_URL + $(GO) run ./cmd/migrate down-one + .PHONY: deps install install-tools deps: ## Download pinned Go module dependencies $(GO) mod download @@ -63,7 +73,7 @@ gen-ml: ## Generate the internal ML service client $(GO_TOOL) ogen -config codegen/ogen-ml.yml --target internal/adapter/secondary/ml/api --package api --clean ../api/ml/openapi.bundle.yml .PHONY: gen-sqlc -gen-sqlc: ## Generate PostgreSQL health query code +gen-sqlc: ## Generate PostgreSQL query code from migrations and queries $(GO_TOOL) sqlc generate -f codegen/sqlc.yml .PHONY: gen-wire diff --git a/backend/cmd/migrate/main.go b/backend/cmd/migrate/main.go new file mode 100644 index 0000000..31a16f6 --- /dev/null +++ b/backend/cmd/migrate/main.go @@ -0,0 +1,116 @@ +// Command migrate applies, inspects, or rolls back the embedded schema +// migrations against DATABASE_URL with the same runner and advisory lock that +// the backend uses at startup. It is intended for local development. +package main + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "os/signal" + "syscall" + "time" + + "lincodex/backend/config" + "lincodex/backend/db" + "lincodex/backend/internal/adapter/secondary/postgres" +) + +const usage = "usage: migrate status|up|down-one" + +func main() { + if err := run(os.Args[1:], os.Stdout); err != nil { + _, _ = fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run(args []string, output io.Writer) (runErr error) { + if len(args) != 1 { + return errors.New("main.run - " + usage) + } + command := args[0] + databaseURL := config.DatabaseURLFromEnv(os.LookupEnv) + if databaseURL == "" { + return errors.New("main.run - DATABASE_URL is not set") + } + migrations, err := db.Migrations() + if err != nil { + return fmt.Errorf("main.run - load migrations: %w", err) + } + migrator, err := postgres.NewMigrator(databaseURL, migrations) + if err != nil { + return fmt.Errorf("main.run - create migrator: %w", err) + } + defer func() { + if err := migrator.Close(); err != nil { + runErr = errors.Join(runErr, fmt.Errorf("main.run - close migrator: %w", err)) + } + }() + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + switch command { + case "status": + return printStatus(ctx, migrator, output) + case "up": + return applyUp(ctx, migrator, output) + case "down-one": + return rollBackOne(ctx, migrator, output) + default: + return errors.New("main.run - " + usage) + } +} + +func printStatus(ctx context.Context, migrator *postgres.Migrator, output io.Writer) error { + statuses, err := migrator.Status(ctx) + if err != nil { + return fmt.Errorf("main.printStatus - read status: %w", err) + } + for _, status := range statuses { + appliedAt := "pending" + if status.Applied { + appliedAt = status.AppliedAt.UTC().Format(time.RFC3339) + } + if _, err := fmt.Fprintf(output, "%-20s %s\n", appliedAt, status.Name); err != nil { + return fmt.Errorf("main.printStatus - write status: %w", err) + } + } + return nil +} + +func applyUp(ctx context.Context, migrator *postgres.Migrator, output io.Writer) error { + applied, err := migrator.Up(ctx) + if err != nil { + return fmt.Errorf("main.applyUp - apply migrations: %w", err) + } + for _, migration := range applied { + if _, err := fmt.Fprintf(output, "applied %s (%s)\n", migration.Name, migration.Duration); err != nil { + return fmt.Errorf("main.applyUp - write result: %w", err) + } + } + if _, err := fmt.Fprintf(output, "%d migration(s) applied\n", len(applied)); err != nil { + return fmt.Errorf("main.applyUp - write summary: %w", err) + } + return nil +} + +func rollBackOne(ctx context.Context, migrator *postgres.Migrator, output io.Writer) error { + migration, err := migrator.DownOne(ctx) + if errors.Is(err, postgres.ErrNoMigrationToRollBack) { + _, writeErr := fmt.Fprintln(output, "no applied migration to roll back") + if writeErr != nil { + return fmt.Errorf("main.rollBackOne - write result: %w", writeErr) + } + return nil + } + if err != nil { + return fmt.Errorf("main.rollBackOne - roll back migration: %w", err) + } + if _, err := fmt.Fprintf(output, "rolled back %s (%s)\n", migration.Name, migration.Duration); err != nil { + return fmt.Errorf("main.rollBackOne - write result: %w", err) + } + return nil +} diff --git a/backend/config/config.go b/backend/config/config.go index b6fa307..d27bd55 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -18,27 +18,32 @@ const ( defaultRedisTimeout = time.Second defaultReadinessTimeout = time.Second defaultShutdownTimeout = 10 * time.Second - maxPortNumber = 65535 + // Startup migrations are on by default so a deployed binary never serves + // with a schema older than the one it was built for. + defaultDatabaseMigrateOnStart = true + maxPortNumber = 65535 ) type Config struct { - HTTPAddr string - MetricsAddr string - DatabaseURL string - RedisAddr string - RedisPassword string - RedisDB int - RedisTimeout time.Duration - SeaweedFSEndpoint string - SeaweedFSAccessKey string - SeaweedFSSecretKey string - SeaweedFSBucket string - SeaweedFSRegion string - SeaweedFSTimeout time.Duration - KafkaBrokers []string - LogLevel string - ReadinessTimeout time.Duration - ShutdownTimeout time.Duration + HTTPAddr string + MetricsAddr string + DatabaseURL string + // DatabaseMigrateOnStart applies embedded migrations before serving. + DatabaseMigrateOnStart bool + RedisAddr string + RedisPassword string + RedisDB int + RedisTimeout time.Duration + SeaweedFSEndpoint string + SeaweedFSAccessKey string + SeaweedFSSecretKey string + SeaweedFSBucket string + SeaweedFSRegion string + SeaweedFSTimeout time.Duration + KafkaBrokers []string + LogLevel string + ReadinessTimeout time.Duration + ShutdownTimeout time.Duration } type LookupEnv func(string) (string, bool) @@ -51,7 +56,7 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { config := Config{ HTTPAddr: valueOrDefault(lookup, "HTTP_ADDR", defaultHTTPAddr), MetricsAddr: valueOrDefault(lookup, "METRICS_ADDR", defaultMetricsAddr), - DatabaseURL: strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")), + DatabaseURL: DatabaseURLFromEnv(lookup), RedisAddr: strings.TrimSpace(valueOrDefault(lookup, "REDIS_ADDR", defaultRedisAddr)), RedisPassword: valueOrDefault(lookup, "REDIS_PASSWORD", ""), RedisTimeout: defaultRedisTimeout, @@ -72,6 +77,11 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { } var err error + config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart) + if err != nil { + return Config{}, err + } + config.SeaweedFSTimeout, err = durationOrDefault(lookup, "SEAWEEDFS_TIMEOUT", config.SeaweedFSTimeout) if err != nil { return Config{}, err @@ -130,6 +140,30 @@ func valueOrDefault(lookup LookupEnv, key, fallback string) string { return fallback } +// DatabaseURLFromEnv reads DATABASE_URL for commands that need only the +// database, such as the migration command. +func DatabaseURLFromEnv(lookup LookupEnv) string { + return strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")) +} + +// boolOrDefault accepts only "true" or "false", ignoring case and surrounding +// spaces. strconv.ParseBool would also accept 1, t, and similar shorthands, +// which are easy to mistype in deployment files. +func boolOrDefault(lookup LookupEnv, key string, fallback bool) (bool, error) { + value, ok := lookup(key) + if !ok { + return fallback, nil + } + switch strings.ToLower(strings.TrimSpace(value)) { + case "true": + return true, nil + case "false": + return false, nil + default: + return false, fmt.Errorf("config.boolOrDefault - %s must be true or false", key) + } +} + func durationOrDefault(lookup LookupEnv, key string, fallback time.Duration) (time.Duration, error) { value, ok := lookup(key) if !ok { diff --git a/backend/config/config_test.go b/backend/config/config_test.go index 077c28c..6542b62 100644 --- a/backend/config/config_test.go +++ b/backend/config/config_test.go @@ -21,6 +21,9 @@ func TestLoadFromEnvUsesOperationalDefaults(t *testing.T) { if config.DatabaseURL != "" { t.Fatalf("DatabaseURL = %q, want empty", config.DatabaseURL) } + if !config.DatabaseMigrateOnStart { + t.Fatal("DatabaseMigrateOnStart = false, want startup migrations enabled by default") + } if config.RedisAddr != "localhost:6379" || config.RedisDB != 0 || config.RedisTimeout != time.Second || config.RedisPassword != "" { t.Fatalf("unexpected Redis defaults") } @@ -34,16 +37,17 @@ func TestLoadFromEnvUsesOperationalDefaults(t *testing.T) { func TestLoadFromEnvReadsAddressesAndTimeouts(t *testing.T) { values := map[string]string{ - "HTTP_ADDR": "127.0.0.1:18080", - "REDIS_ADDR": "cache:6379", - "REDIS_PASSWORD": " local-secret ", - "REDIS_DB": "2", - "REDIS_TIMEOUT": "500ms", - "METRICS_ADDR": "127.0.0.1:19090", - "DATABASE_URL": " postgres://app:secret@db/app ", - "LOG_LEVEL": " DEBUG ", - "READINESS_TIMEOUT": "2s", - "SHUTDOWN_TIMEOUT": "15s", + "HTTP_ADDR": "127.0.0.1:18080", + "REDIS_ADDR": "cache:6379", + "REDIS_PASSWORD": " local-secret ", + "REDIS_DB": "2", + "REDIS_TIMEOUT": "500ms", + "METRICS_ADDR": "127.0.0.1:19090", + "DATABASE_URL": " postgres://app:secret@db/app ", + "DATABASE_MIGRATE_ON_START": " FALSE ", + "LOG_LEVEL": " DEBUG ", + "READINESS_TIMEOUT": "2s", + "SHUTDOWN_TIMEOUT": "15s", } config, err := LoadFromEnv(testEnvironment(values)) if err != nil { @@ -58,6 +62,9 @@ func TestLoadFromEnvReadsAddressesAndTimeouts(t *testing.T) { if config.DatabaseURL != "postgres://app:secret@db/app" { t.Fatalf("DatabaseURL was not trimmed: %q", config.DatabaseURL) } + if config.DatabaseMigrateOnStart { + t.Fatal("DatabaseMigrateOnStart = true, want the explicit false value") + } if config.LogLevel != "debug" { t.Fatalf("LogLevel was not normalized: %q", config.LogLevel) } @@ -84,6 +91,10 @@ func TestLoadFromEnvRejectsInvalidSettings(t *testing.T) { {name: "negative Redis database", values: map[string]string{"REDIS_DB": "-1"}, want: "Config.ValidateRedis - REDIS_DB"}, {name: "invalid Redis timeout", values: map[string]string{"REDIS_TIMEOUT": "soon"}, want: "config.durationOrDefault - parse REDIS_TIMEOUT"}, {name: "zero Redis timeout", values: map[string]string{"REDIS_TIMEOUT": "0s"}, want: "Config.ValidateRedis - REDIS_TIMEOUT"}, + {name: "invalid migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": "sometimes"}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, + {name: "numeric migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": "1"}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, + {name: "short migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": "t"}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, + {name: "empty migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": ""}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, {name: "invalid log level", values: map[string]string{"LOG_LEVEL": "trace"}, want: "Config.Validate - LOG_LEVEL"}, } for _, test := range tests { diff --git a/backend/db/migrations.go b/backend/db/migrations.go new file mode 100644 index 0000000..61811ed --- /dev/null +++ b/backend/db/migrations.go @@ -0,0 +1,25 @@ +// Package db embeds the versioned SQL migrations so the backend binary applies +// exactly the schema it was built with. The SQL files stay in db/migrations, +// where sqlc and sqlfluff also read them; go:embed cannot reach a parent +// directory, so the embedding package lives next to that directory. +package db + +import ( + "embed" + "fmt" + "io/fs" +) + +const migrationsDirectory = "migrations" + +//go:embed migrations/*.sql +var migrationFiles embed.FS + +// Migrations returns the goose SQL migrations with file names at the root. +func Migrations() (fs.FS, error) { + migrations, err := fs.Sub(migrationFiles, migrationsDirectory) + if err != nil { + return nil, fmt.Errorf("db.Migrations - open embedded migrations: %w", err) + } + return migrations, nil +} diff --git a/backend/db/migrations/.gitkeep b/backend/db/migrations/.gitkeep deleted file mode 100644 index 8b13789..0000000 --- a/backend/db/migrations/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/backend/db/migrations/00001_create_outbox_events.sql b/backend/db/migrations/00001_create_outbox_events.sql new file mode 100644 index 0000000..4e55b5d --- /dev/null +++ b/backend/db/migrations/00001_create_outbox_events.sql @@ -0,0 +1,54 @@ +-- +goose Up +-- Transactional outbox: a business transaction appends its domain events here +-- in the same PostgreSQL transaction as the business change. A relay publishes +-- unpublished rows to Kafka. Payloads carry identifiers and minimal facts only, +-- never contact data, tokens, passwords, or document contents. +CREATE TABLE outbox_events ( + -- Monotonic insertion key for the relay scan. It is assigned at insert + -- time, so a transaction that waited on a row lock gets a larger value + -- than the transaction it waited for. + position bigint GENERATED ALWAYS AS IDENTITY, + event_id uuid NOT NULL, + event_type text NOT NULL, + schema_version integer NOT NULL, + aggregate_type text NOT NULL, + aggregate_id uuid NOT NULL, + aggregate_version bigint NOT NULL, + payload jsonb NOT NULL, + -- Statement time rather than transaction start time. Informational only: + -- ordering uses position and aggregate_version. + occurred_at timestamptz NOT NULL DEFAULT clock_timestamp(), + published_at timestamptz, + CONSTRAINT outbox_events_pkey PRIMARY KEY (event_id), + CONSTRAINT outbox_events_position_key UNIQUE (position), + CONSTRAINT outbox_events_aggregate_version_event_type_key UNIQUE ( + aggregate_type, aggregate_id, aggregate_version, event_type + ), + CONSTRAINT outbox_events_event_type_format CHECK ( + char_length(event_type) <= 128 + AND event_type ~ '^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$' + ), + CONSTRAINT outbox_events_schema_version_positive CHECK (schema_version > 0), + CONSTRAINT outbox_events_aggregate_type_format CHECK ( + char_length(aggregate_type) <= 64 + AND aggregate_type ~ '^[a-z][a-z0-9_]*$' + ), + CONSTRAINT outbox_events_aggregate_version_positive CHECK ( + aggregate_version > 0 + ), + -- The payload size limit is enforced in Go on compact JSON. The jsonb text + -- and binary forms differ in size from that input, so a database length + -- check could reject an event that the domain accepted. + CONSTRAINT outbox_events_payload_object CHECK ( + jsonb_typeof(payload) = 'object' + ) +); + +-- Supports the relay scan of unpublished events in insertion order. The index +-- shrinks as events are published. +CREATE INDEX outbox_events_unpublished_idx +ON outbox_events (position) +WHERE published_at IS NULL; + +-- +goose Down +DROP TABLE outbox_events; diff --git a/backend/db/migrations_test.go b/backend/db/migrations_test.go new file mode 100644 index 0000000..3a37086 --- /dev/null +++ b/backend/db/migrations_test.go @@ -0,0 +1,44 @@ +package db + +import ( + "io/fs" + "regexp" + "strings" + "testing" +) + +var migrationNamePattern = regexp.MustCompile(`^[0-9]{5}_[a-z0-9_]+\.sql$`) + +// TestMigrationsHaveSequentialNamesAndBothDirections runs without a database so +// make -C backend check catches a malformed or one-way migration. +func TestMigrationsHaveSequentialNamesAndBothDirections(t *testing.T) { + migrations, err := Migrations() + if err != nil { + t.Fatalf("Migrations() error = %v", err) + } + names, err := fs.Glob(migrations, "*.sql") + if err != nil { + t.Fatalf("list migrations: %v", err) + } + if len(names) == 0 { + t.Fatal("no embedded migrations") + } + for _, name := range names { + if !migrationNamePattern.MatchString(name) { + t.Fatalf("migration %s does not match NNNNN_description.sql", name) + } + content, err := fs.ReadFile(migrations, name) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + text := string(content) + up := strings.Index(text, "-- +goose Up") + down := strings.Index(text, "-- +goose Down") + if up < 0 || down < up { + t.Fatalf("migration %s needs a -- +goose Up section followed by a -- +goose Down section", name) + } + if strings.TrimSpace(text[down+len("-- +goose Down"):]) == "" { + t.Fatalf("migration %s has an empty Down section", name) + } + } +} diff --git a/backend/db/queries/outbox.sql b/backend/db/queries/outbox.sql new file mode 100644 index 0000000..0d5cbad --- /dev/null +++ b/backend/db/queries/outbox.sql @@ -0,0 +1,18 @@ +-- name: InsertOutboxEvent :exec +INSERT INTO outbox_events ( + event_id, + event_type, + schema_version, + aggregate_type, + aggregate_id, + aggregate_version, + payload +) VALUES ( + sqlc.arg(event_id), + sqlc.arg(event_type), + sqlc.arg(schema_version), + sqlc.arg(aggregate_type), + sqlc.arg(aggregate_id), + sqlc.arg(aggregate_version), + sqlc.arg(payload) +); diff --git a/backend/go.mod b/backend/go.mod index f6067a8..f8da735 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -12,8 +12,10 @@ require ( github.com/go-faster/errors v0.8.0 github.com/go-faster/jx v1.2.0 github.com/goforj/wire v1.2.0 + github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.11.0 github.com/ogen-go/ogen v1.24.0 + github.com/pressly/goose/v3 v3.28.0 github.com/prometheus/client_golang v1.24.1 github.com/redis/go-redis/v9 v9.22.0 github.com/testcontainers/testcontainers-go v0.44.0 @@ -182,7 +184,6 @@ require ( github.com/google/cel-go v0.28.0 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/google/subcommands v1.2.0 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/gordonklaus/ineffassign v0.2.0 // indirect github.com/gostaticanalysis/analysisutil v0.7.1 // indirect github.com/gostaticanalysis/comment v1.5.0 // indirect @@ -283,7 +284,6 @@ require ( github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect - github.com/pressly/goose/v3 v3.28.0 // indirect github.com/prometheus/client_model v0.6.3 // indirect github.com/prometheus/common v0.72.0 // indirect github.com/prometheus/procfs v0.22.0 // indirect diff --git a/backend/integration_test/bootstrap_test.go b/backend/integration_test/bootstrap_test.go index d80e173..a3becac 100644 --- a/backend/integration_test/bootstrap_test.go +++ b/backend/integration_test/bootstrap_test.go @@ -152,6 +152,7 @@ func (env *testEnvironment) startPostgres(ctx context.Context, t *testing.T) { if err := env.Postgres.Check(ctx); err != nil { t.Fatalf("PostgreSQL readiness: %v", err) } + applyMigrations(ctx, t, env.Config.DatabaseURL) } func (env *testEnvironment) startRedis(ctx context.Context, t *testing.T) { diff --git a/backend/integration_test/outbox_test.go b/backend/integration_test/outbox_test.go new file mode 100644 index 0000000..aeb1d3c --- /dev/null +++ b/backend/integration_test/outbox_test.go @@ -0,0 +1,654 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "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" +) + +const ( + // The test aggregate lives in its own schema, outside production migrations. + testAggregateSchema = "outbox_test" + testAggregateTable = "accounts" + testAggregateType = "test_account" + testAccountEventType = "test.account_changed" + testEventSchema = 1 + parallelTransactions = 20 + contenderCount = 2 + outboxTestTimeout = 2 * time.Minute + lockWaitTimeout = 10 * time.Second + connectionsTimeout = 5 * time.Second + canceledFnTimeout = 300 * time.Millisecond + pollInterval = 10 * time.Millisecond + checkViolationCode = "23514" + accountStatusActive = "active" + accountStatusArchived = "archived" + contenderApplication = "outbox_contender_b" +) + +var ( + errForcedRollback = errors.New("forced rollback") + errStaleAccountVersion = errors.New("test account version is stale") + outboxEventsTable = pgx.Identifier{"outbox_events"} + testAccountsTable = pgx.Identifier{testAggregateSchema, testAggregateTable} + createTestAccountsTable = fmt.Sprintf(` + CREATE SCHEMA %[1]s; + CREATE TABLE %[2]s ( + id uuid PRIMARY KEY, + version bigint NOT NULL CHECK (version > 0), + status text NOT NULL + )`, pgx.Identifier{testAggregateSchema}.Sanitize(), testAccountsTable.Sanitize()) +) + +type testAccount struct { + id uuid.UUID + version int64 + status string +} + +type storedEvent struct { + position int64 + eventID uuid.UUID + eventType string + schemaVersion int32 + aggregateType string + aggregateID uuid.UUID + aggregateVersion int64 + payload []byte + publishedAt *time.Time +} + +type transactionFn = func(context.Context, outbound.UnitOfWork) error + +func TestOutboxTransactions(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), outboxTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + if _, err := pool.Exec(ctx, createTestAccountsTable); err != nil { + t.Fatalf("create test aggregate table: %v", err) + } + transactor := postgresadapter.NewTransactor(pool) + + // Subtests share tables and run sequentially; each starts from empty tables. + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, outboxEventsTable, testAccountsTable) + } + + t.Run("commits the aggregate change and its event together", func(t *testing.T) { + reset(t) + created := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + createdEvent := newAccountEvent(t, created) + if err := transactor.WithinTransaction(ctx, saveAccountWith(created, createdEvent)); err != nil { + t.Fatalf("WithinTransaction(create) error = %v", err) + } + archived := testAccount{id: created.id, version: 2, status: accountStatusArchived} + archivedEvent := newAccountEvent(t, archived) + if err := transactor.WithinTransaction(ctx, saveAccountWith(archived, archivedEvent)); err != nil { + t.Fatalf("WithinTransaction(update) error = %v", err) + } + + assertAccount(ctx, t, pool, archived) + events := readOutboxEvents(ctx, t, pool) + if len(events) != 2 { + t.Fatalf("outbox has %d events, want 2", len(events)) + } + assertStoredEvent(t, events[0], createdEvent) + assertStoredEvent(t, events[1], archivedEvent) + if events[0].position >= events[1].position { + t.Fatalf("positions %d and %d do not follow insertion order", events[0].position, events[1].position) + } + assertNoBusyConnections(t, pool) + }) + + t.Run("optimistic version check rejects a stale update before the event", func(t *testing.T) { + reset(t) + created := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + if err := transactor.WithinTransaction(ctx, saveAccountWith(created, newAccountEvent(t, created))); err != nil { + t.Fatalf("WithinTransaction(create) error = %v", err) + } + updated := testAccount{id: created.id, version: 2, status: accountStatusArchived} + if err := transactor.WithinTransaction(ctx, saveAccountWith(updated, newAccountEvent(t, updated))); err != nil { + t.Fatalf("WithinTransaction(update) error = %v", err) + } + // A writer that still expects version 1 must fail on the version check. + stale := testAccount{id: created.id, version: 2, status: "stale"} + err := transactor.WithinTransaction(ctx, saveAccountWith(stale, newAccountEvent(t, stale))) + if !errors.Is(err, errStaleAccountVersion) { + t.Fatalf("WithinTransaction(stale) error = %v, want errStaleAccountVersion", err) + } + assertAccount(ctx, t, pool, updated) + if events := readOutboxEvents(ctx, t, pool); len(events) != 2 { + t.Fatalf("outbox has %d events, want 2", len(events)) + } + assertNoBusyConnections(t, pool) + }) + + t.Run("rolls back both writes when the callback fails", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + return errForcedRollback + }) + if !errors.Is(err, errForcedRollback) { + t.Fatalf("WithinTransaction() error = %v, want the callback error", err) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("rolls back both writes and re-raises a panic", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + panicValue := fmt.Sprintf("forced panic %s", account.id) + recovered := func() (recovered any) { + defer func() { recovered = recover() }() + _ = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + panic(panicValue) + }) + return nil + }() + if recovered != panicValue { + t.Fatalf("recovered %v, want the original panic value", recovered) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("rolls back and releases the connection when the context is canceled mid-callback", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + callbackCtx, cancelCallback := context.WithTimeout(ctx, canceledFnTimeout) + defer cancelCallback() + err := transactor.WithinTransaction(callbackCtx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + // The deadline interrupts this statement after both writes. + _, err := integrationTx(t, unit).Exec(ctx, "SELECT pg_sleep(30)") + return err + }) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("WithinTransaction() error = %v, want context.DeadlineExceeded", err) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("rejects a nested transaction without touching the outer one", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + innerRan := false + var nestedErr error + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + nestedErr = transactor.WithinTransaction(ctx, func(context.Context, outbound.UnitOfWork) error { + innerRan = true + return nil + }) + return nil + }) + if err != nil { + t.Fatalf("outer WithinTransaction() error = %v", err) + } + if !errors.Is(nestedErr, outbound.ErrNestedTransaction) || innerRan { + t.Fatalf("nested WithinTransaction() error = %v, inner ran = %t, want ErrNestedTransaction without running", nestedErr, innerRan) + } + assertAccount(ctx, t, pool, account) + assertNoBusyConnections(t, pool) + }) + + t.Run("fails the commit when the callback ignores a statement error", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + event := newAccountEvent(t, account) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := saveAccountWith(account, event)(ctx, unit); err != nil { + return err + } + // The duplicate aborts the transaction even though the error is dropped. + if err := unit.Outbox().Append(ctx, event); !errors.Is(err, outbound.ErrOutboxEventConflict) { + return fmt.Errorf("duplicate append error = %w, want ErrOutboxEventConflict", err) + } + return nil + }) + if !errors.Is(err, pgx.ErrTxCommitRollback) { + t.Fatalf("WithinTransaction() error = %v, want pgx.ErrTxCommitRollback", err) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("stores every domain-valid edge payload", func(t *testing.T) { + reset(t) + prefix, suffix := `{"ids":[`, `0]}` + arrayAtLimit := prefix + strings.Repeat("0,", (domain.MaxDomainEventPayloadBytes-len(prefix)-len(suffix))/2) + suffix + payloads := []string{ + arrayAtLimit, + strings.Repeat(`{"a":`, 32) + "1" + strings.Repeat("}", 32), + `{"text":"\\u0000 is plain text here"}`, + `{"name":"Привет","emoji":"😀"}`, + `{"big":123456789012345678901234567890,"small":1e-300}`, + } + events := make([]domain.DomainEvent, 0, len(payloads)) + for _, payload := range payloads { + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: testAccountEventType, SchemaVersion: testEventSchema, AggregateType: testAggregateType, + AggregateID: uuid.New(), AggregateVersion: 1, Payload: []byte(payload), + }) + if err != nil { + t.Fatalf("NewDomainEvent(%.40s) error = %v", payload, err) + } + events = append(events, event) + } + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Outbox().Append(ctx, events...) + }) + if err != nil { + t.Fatalf("Append(edge payloads) error = %v", err) + } + stored := readOutboxEvents(ctx, t, pool) + byID := make(map[uuid.UUID]storedEvent, len(stored)) + for _, event := range stored { + byID[event.eventID] = event + } + for _, event := range events { + assertStoredEvent(t, byID[event.EventID()], event) + } + }) + + t.Run("parallel transactions commit independently and a lock waiter conflicts on the aggregate version", func(t *testing.T) { + reset(t) + // One connection per transaction plus a spare, so nothing queues in the pool. + concurrentPool := env.newPoolWithMaxConns(ctx, t, parallelTransactions+contenderCount+1) + concurrentTransactor := postgresadapter.NewTransactor(concurrentPool) + contested := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + if err := transactor.WithinTransaction(ctx, saveAccountWith(contested, newAccountEvent(t, contested))); err != nil { + t.Fatalf("create contested account: %v", err) + } + + // The contenders deliberately skip the optimistic version check to prove + // that the outbox unique key still blocks a second event for version 2. + // A holds its transaction open after writing; B then blocks on A's row + // lock and, once A commits, violates the outbox key. + contenderA := testAccount{id: contested.id, version: 2, status: "contender_a"} + contenderB := testAccount{id: contested.id, version: 2, status: "contender_b"} + writeA := blindSaveAccountWith(contenderA, newAccountEvent(t, contenderA)) + writeB := blindSaveAccountWith(contenderB, newAccountEvent(t, contenderB)) + aWrote, releaseA, aFinished := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(releaseA) }) } + defer release() + + independent := make([]transactionFn, 0, parallelTransactions) + for range parallelTransactions { + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + independent = append(independent, saveAccountWith(account, newAccountEvent(t, account))) + } + independentErrs := make([]error, len(independent)) + var errA, errB error + start := make(chan struct{}) + var group sync.WaitGroup + for index, write := range independent { + group.Go(func() { + <-start + independentErrs[index] = concurrentTransactor.WithinTransaction(ctx, write) + }) + } + group.Go(func() { + defer close(aFinished) + <-start + errA = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := writeA(ctx, unit); err != nil { + return err + } + close(aWrote) + select { + case <-releaseA: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }) + }) + group.Go(func() { + select { + case <-aWrote: + case <-aFinished: + errB = errors.New("contender A finished before writing") + return + } + errB = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + // Label the session so the test can observe its lock wait. + if _, err := integrationTx(t, unit).Exec(ctx, "SET LOCAL application_name = '"+contenderApplication+"'"); err != nil { + return fmt.Errorf("label contender B: %w", err) + } + return writeB(ctx, unit) + }) + }) + close(start) + + waitEvent, observed := waitForLockWait(ctx, pool, contenderApplication) + release() + group.Wait() + if !observed { + t.Fatalf("contender B was not observed waiting on a lock (last wait event %q)", waitEvent) + } + t.Logf("observed contender B waiting on a lock: wait_event=%s", waitEvent) + + for index, err := range independentErrs { + if err != nil { + t.Fatalf("independent transaction %d error = %v", index, err) + } + } + if errA != nil { + t.Fatalf("contender A error = %v", errA) + } + if !errors.Is(errB, outbound.ErrOutboxEventConflict) { + t.Fatalf("contender B error = %v, want ErrOutboxEventConflict", errB) + } + + assertAccount(ctx, t, pool, contenderA) + events := readOutboxEvents(ctx, t, pool) + if want := 1 + parallelTransactions + 1; len(events) != want { + t.Fatalf("outbox has %d events, want %d", len(events), want) + } + var orphans int + err := pool.QueryRow(ctx, fmt.Sprintf(` + SELECT count(*) FROM outbox_events AS e + WHERE NOT EXISTS ( + SELECT 1 FROM %s AS a + WHERE a.id = e.aggregate_id AND a.version >= e.aggregate_version + )`, testAccountsTable.Sanitize())).Scan(&orphans) + if err != nil { + t.Fatalf("count orphan events: %v", err) + } + if orphans != 0 { + t.Fatalf("found %d events without their aggregate change", orphans) + } + var winnerPayload []byte + err = pool.QueryRow(ctx, ` + SELECT payload FROM outbox_events + WHERE aggregate_id = $1 AND aggregate_version = 2`, contested.id).Scan(&winnerPayload) + if err != nil { + t.Fatalf("read contested event: %v", err) + } + assertJSONEqual(t, winnerPayload, accountPayload(contenderA)) + assertNoBusyConnections(t, concurrentPool) + assertNoBusyConnections(t, pool) + }) + + t.Run("domain validation and database constraints reject invalid versions", func(t *testing.T) { + reset(t) + for _, input := range []domain.DomainEventInput{ + {EventType: testAccountEventType, SchemaVersion: 0, AggregateType: testAggregateType, AggregateID: uuid.New(), AggregateVersion: 1, Payload: []byte(`{}`)}, + {EventType: testAccountEventType, SchemaVersion: 1, AggregateType: testAggregateType, AggregateID: uuid.New(), AggregateVersion: 0, Payload: []byte(`{}`)}, + } { + if _, err := domain.NewDomainEvent(input); !errors.Is(err, domain.ErrInvalidDomainEvent) { + t.Fatalf("NewDomainEvent(%+v) error = %v, want ErrInvalidDomainEvent", input, err) + } + } + + tests := []struct { + constraint string + schemaVersion int32 + aggregateVersion int64 + payload string + }{ + {constraint: "outbox_events_schema_version_positive", schemaVersion: 0, aggregateVersion: 1, payload: `{}`}, + {constraint: "outbox_events_aggregate_version_positive", schemaVersion: 1, aggregateVersion: 0, payload: `{}`}, + {constraint: "outbox_events_payload_object", schemaVersion: 1, aggregateVersion: 1, payload: `[]`}, + } + for _, test := range tests { + // Raw SQL bypasses domain validation to prove the database backstop. + _, err := pool.Exec(ctx, ` + INSERT INTO outbox_events ( + event_id, event_type, schema_version, aggregate_type, + aggregate_id, aggregate_version, payload + ) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)`, + uuid.New(), testAccountEventType, test.schemaVersion, testAggregateType, + uuid.New(), test.aggregateVersion, test.payload) + 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) + } + } + assertTablesEmpty(ctx, t, pool) + }) +} + +// integrationTx returns the transaction behind unit through the adapter's +// integration-only seam. +func integrationTx(t *testing.T, unit outbound.UnitOfWork) pgx.Tx { + t.Helper() + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + t.Errorf("unit of work has type %T, want the PostgreSQL adapter", unit) + } + return tx +} + +// saveAccountWith returns a transaction callback that writes the aggregate +// with an optimistic version check and then its event through the same unit +// of work. Version 1 inserts; later versions update from the previous version. +func saveAccountWith(account testAccount, event domain.DomainEvent) transactionFn { + insert := fmt.Sprintf(`INSERT INTO %s (id, version, status) VALUES ($1, $2, $3)`, testAccountsTable.Sanitize()) + update := fmt.Sprintf(`UPDATE %s SET version = $2, status = $3 WHERE id = $1 AND version = $2 - 1`, testAccountsTable.Sanitize()) + return func(ctx context.Context, unit outbound.UnitOfWork) error { + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + return fmt.Errorf("unit of work has type %T, want the PostgreSQL adapter", unit) + } + statement := update + if account.version == 1 { + statement = insert + } + tag, err := tx.Exec(ctx, statement, account.id, account.version, account.status) + if err != nil { + return fmt.Errorf("save test account: %w", err) + } + if tag.RowsAffected() != 1 { + return errStaleAccountVersion + } + return unit.Outbox().Append(ctx, event) + } +} + +// blindSaveAccountWith overwrites the aggregate without a version check. Only +// the contention test uses it, to exercise the outbox uniqueness backstop. +func blindSaveAccountWith(account testAccount, event domain.DomainEvent) transactionFn { + update := fmt.Sprintf(`UPDATE %s SET version = $2, status = $3 WHERE id = $1`, testAccountsTable.Sanitize()) + return func(ctx context.Context, unit outbound.UnitOfWork) error { + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + return fmt.Errorf("unit of work has type %T, want the PostgreSQL adapter", unit) + } + if _, err := tx.Exec(ctx, update, account.id, account.version, account.status); err != nil { + return fmt.Errorf("overwrite test account: %w", err) + } + return unit.Outbox().Append(ctx, event) + } +} + +// waitForLockWait polls pg_stat_activity until the session labeled +// applicationName waits on a heavyweight lock. +func waitForLockWait(ctx context.Context, pool *pgxpool.Pool, applicationName string) (string, bool) { + ctx, cancel := context.WithTimeout(ctx, lockWaitTimeout) + defer cancel() + ticker := time.NewTicker(pollInterval) + defer ticker.Stop() + lastWaitEvent := "" + for { + var waitEventType, waitEvent *string + err := pool.QueryRow(ctx, ` + SELECT wait_event_type, wait_event FROM pg_stat_activity + WHERE application_name = $1 AND state = 'active'`, applicationName).Scan(&waitEventType, &waitEvent) + if err == nil && waitEventType != nil && *waitEventType == "Lock" { + if waitEvent != nil { + return *waitEvent, true + } + return "", true + } + if err == nil && waitEvent != nil { + lastWaitEvent = *waitEvent + } + select { + case <-ctx.Done(): + return lastWaitEvent, false + case <-ticker.C: + } + } +} + +func accountPayload(account testAccount) []byte { + payload, err := json.Marshal(map[string]any{ + "account_id": account.id.String(), + "status": account.status, + }) + if err != nil { + panic(err) + } + return payload +} + +func newAccountEvent(t *testing.T, account testAccount) domain.DomainEvent { + t.Helper() + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: testAccountEventType, + SchemaVersion: testEventSchema, + AggregateType: testAggregateType, + AggregateID: account.id, + AggregateVersion: account.version, + Payload: accountPayload(account), + }) + if err != nil { + t.Fatalf("NewDomainEvent() error = %v", err) + } + return event +} + +func readOutboxEvents(ctx context.Context, t *testing.T, pool *pgxpool.Pool) []storedEvent { + t.Helper() + rows, err := pool.Query(ctx, ` + SELECT position, event_id, event_type, schema_version, aggregate_type, + aggregate_id, aggregate_version, payload, published_at + FROM outbox_events + ORDER BY position`) + if err != nil { + t.Fatalf("query outbox events: %v", err) + } + events, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (storedEvent, error) { + var event storedEvent + err := row.Scan(&event.position, &event.eventID, &event.eventType, &event.schemaVersion, &event.aggregateType, + &event.aggregateID, &event.aggregateVersion, &event.payload, &event.publishedAt) + return event, err + }) + if err != nil { + t.Fatalf("read outbox events: %v", err) + } + return events +} + +func assertStoredEvent(t *testing.T, stored storedEvent, want domain.DomainEvent) { + t.Helper() + if stored.eventID != want.EventID() || stored.eventType != want.EventType() || + stored.schemaVersion != want.SchemaVersion() || stored.aggregateType != want.AggregateType() || + stored.aggregateID != want.AggregateID() || stored.aggregateVersion != want.AggregateVersion() { + t.Fatalf("stored event %+v does not match written event %s v%d", stored, want.EventID(), want.AggregateVersion()) + } + if stored.publishedAt != nil { + t.Fatalf("new event %s is already marked as published", stored.eventID) + } + assertJSONEqual(t, stored.payload, want.Payload()) +} + +// assertJSONEqual compares JSON values because jsonb normalizes key order and +// whitespace. +func assertJSONEqual(t *testing.T, got, want []byte) { + t.Helper() + var gotValue, wantValue any + if err := json.Unmarshal(got, &gotValue); err != nil { + t.Fatalf("decode stored payload: %v", err) + } + if err := json.Unmarshal(want, &wantValue); err != nil { + t.Fatalf("decode expected payload: %v", err) + } + if !reflect.DeepEqual(gotValue, wantValue) { + t.Fatalf("payload = %.200s, want %.200s", got, want) + } +} + +func assertAccount(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want testAccount) { + t.Helper() + got := testAccount{id: want.id} + err := pool.QueryRow(ctx, fmt.Sprintf(`SELECT version, status FROM %s WHERE id = $1`, testAccountsTable.Sanitize()), + want.id).Scan(&got.version, &got.status) + if err != nil { + t.Fatalf("read test account: %v", err) + } + if got != want { + t.Fatalf("account = %+v, want %+v", got, want) + } +} + +func assertTablesEmpty(ctx context.Context, t *testing.T, pool *pgxpool.Pool) { + t.Helper() + for _, table := range []pgx.Identifier{testAccountsTable, outboxEventsTable} { + var count int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM "+table.Sanitize()).Scan(&count); err != nil { + t.Fatalf("count rows in %s: %v", table.Sanitize(), err) + } + if count != 0 { + t.Fatalf("%s has %d rows after rollback, want 0", table.Sanitize(), count) + } + } +} + +// assertNoBusyConnections proves that every transaction released its +// connection, including after a rollback, a panic, or a canceled query. pgx +// may destroy a connection broken by cancellation asynchronously, so the +// check polls briefly. +func assertNoBusyConnections(t *testing.T, pool *pgxpool.Pool) { + t.Helper() + deadline := time.Now().Add(connectionsTimeout) + for { + acquired := pool.Stat().AcquiredConns() + if acquired == 0 { + return + } + if time.Now().After(deadline) { + t.Fatalf("pool has %d acquired connections after the transactions finished", acquired) + } + time.Sleep(pollInterval) + } +} diff --git a/backend/integration_test/postgres_helpers_test.go b/backend/integration_test/postgres_helpers_test.go new file mode 100644 index 0000000..bfb9970 --- /dev/null +++ b/backend/integration_test/postgres_helpers_test.go @@ -0,0 +1,137 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/rand" + "io/fs" + "net/url" + "strings" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/db" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" +) + +// applyMigrations brings the database at databaseURL to the latest embedded +// schema with the same runner the backend uses at startup. +func applyMigrations(ctx context.Context, t *testing.T, databaseURL string) { + t.Helper() + migrator := newMigrator(t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("apply migrations: %v", err) + } +} + +func newMigrator(t *testing.T, databaseURL string) *postgresadapter.Migrator { + t.Helper() + migrations, err := db.Migrations() + if err != nil { + t.Fatalf("load embedded migrations: %v", err) + } + migrator, err := postgresadapter.NewMigrator(databaseURL, migrations) + if err != nil { + t.Fatalf("create migrator: %v", err) + } + t.Cleanup(func() { + if err := migrator.Close(); err != nil { + t.Errorf("close migrator: %v", err) + } + }) + return migrator +} + +// embeddedMigrationCount derives the expected count from the embedded files. +func embeddedMigrationCount(t *testing.T) int { + t.Helper() + migrations, err := db.Migrations() + if err != nil { + t.Fatalf("load embedded migrations: %v", err) + } + files, err := fs.Glob(migrations, "*.sql") + if err != nil { + t.Fatalf("list embedded migrations: %v", err) + } + if len(files) == 0 { + t.Fatal("no embedded migrations") + } + return len(files) +} + +// newPool opens a pool to the bootstrap database and closes it with t. +func (env *testEnvironment) newPool(ctx context.Context, t *testing.T) *pgxpool.Pool { + t.Helper() + return newPoolFor(ctx, t, env.Config.DatabaseURL) +} + +func newPoolFor(ctx context.Context, t *testing.T, databaseURL string) *pgxpool.Pool { + t.Helper() + pool, err := postgresadapter.NewPool(ctx, databaseURL) + if err != nil { + t.Fatalf("create PostgreSQL pool: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// newPoolWithMaxConns opens a pool sized for a concurrency test, so goroutines +// run their transactions at the same time instead of queueing for connections. +func (env *testEnvironment) newPoolWithMaxConns(ctx context.Context, t *testing.T, maxConns int32) *pgxpool.Pool { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap 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 +} + +// createIsolatedDatabase creates an empty database in the bootstrap container +// for tests that must change the whole schema, and drops it with t. +func (env *testEnvironment) createIsolatedDatabase(ctx context.Context, t *testing.T) string { + t.Helper() + if env.Config.DatabaseURL == "" { + t.Fatal("PostgreSQL was not selected in bootstrap") + } + admin := env.newPool(ctx, t) + name := "isolated_" + strings.ToLower(rand.Text()) + identifier := pgx.Identifier{name}.Sanitize() + if _, err := admin.Exec(ctx, "CREATE DATABASE "+identifier); err != nil { + t.Fatalf("create isolated database: %v", err) + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout) + defer cancel() + if _, err := admin.Exec(ctx, "DROP DATABASE IF EXISTS "+identifier+" WITH (FORCE)"); err != nil { + t.Errorf("drop isolated database: %v", err) + } + }) + databaseURL, err := url.Parse(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + databaseURL.Path = "/" + name + return databaseURL.String() +} + +// truncateTables resets shared tables between sequential subtests. Callers +// must not run subtests that use these tables in parallel. +func truncateTables(ctx context.Context, t *testing.T, pool *pgxpool.Pool, tables ...pgx.Identifier) { + t.Helper() + names := make([]string, 0, len(tables)) + for _, table := range tables { + names = append(names, table.Sanitize()) + } + if _, err := pool.Exec(ctx, "TRUNCATE "+strings.Join(names, ", ")); err != nil { + t.Fatalf("truncate test tables: %v", err) + } +} diff --git a/backend/integration_test/postgres_migrations_test.go b/backend/integration_test/postgres_migrations_test.go new file mode 100644 index 0000000..137fef2 --- /dev/null +++ b/backend/integration_test/postgres_migrations_test.go @@ -0,0 +1,141 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" +) + +const ( + migrationTestTimeout = 3 * time.Minute + concurrentMigrators = 4 +) + +func TestPostgresMigrations(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + total := embeddedMigrationCount(t) + + t.Run("bootstrap database has every migration applied", func(t *testing.T) { + assertAllApplied(ctx, t, newMigrator(t, env.Config.DatabaseURL), total) + }) + + t.Run("up, down to zero, and up again on an isolated database", func(t *testing.T) { + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + + applied, err := migrator.Up(ctx) + if err != nil { + t.Fatalf("first Up() error = %v", err) + } + if len(applied) != total { + t.Fatalf("first Up() applied %d migrations, want %d", len(applied), total) + } + assertOutboxTableExists(ctx, t, pool, true) + + for rolledBack := 0; ; rolledBack++ { + _, err := migrator.DownOne(ctx) + if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) { + if rolledBack != total { + t.Fatalf("rolled back %d migrations, want %d", rolledBack, total) + } + break + } + if err != nil { + t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err) + } + } + assertOutboxTableExists(ctx, t, pool, false) + var leftovers int + err = pool.QueryRow(ctx, ` + SELECT count(*) FROM pg_catalog.pg_class AS c + JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname NOT LIKE 'goose_db_version%'`).Scan(&leftovers) + if err != nil { + t.Fatalf("count leftover relations: %v", err) + } + if leftovers != 0 { + t.Fatalf("%d relations remain after rolling back every migration", leftovers) + } + + applied, err = migrator.Up(ctx) + if err != nil { + t.Fatalf("second Up() error = %v", err) + } + if len(applied) != total { + t.Fatalf("second Up() applied %d migrations, want %d", len(applied), total) + } + assertOutboxTableExists(ctx, t, pool, true) + assertAllApplied(ctx, t, migrator, total) + }) + + t.Run("concurrent runners apply each migration once", func(t *testing.T) { + databaseURL := env.createIsolatedDatabase(ctx, t) + migrators := make([]*postgresadapter.Migrator, concurrentMigrators) + for index := range migrators { + migrators[index] = newMigrator(t, databaseURL) + } + applied := make([]int, len(migrators)) + errs := make([]error, len(migrators)) + start := make(chan struct{}) + var group sync.WaitGroup + for index, migrator := range migrators { + group.Go(func() { + <-start + results, err := migrator.Up(ctx) + applied[index], errs[index] = len(results), err + }) + } + close(start) + group.Wait() + + sum := 0 + for index, err := range errs { + if err != nil { + t.Fatalf("runner %d Up() error = %v", index, err) + } + sum += applied[index] + } + if sum != total { + t.Fatalf("runners applied %d migrations in total, want %d", sum, total) + } + assertAllApplied(ctx, t, migrators[0], total) + }) +} + +func assertAllApplied(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator, total int) { + t.Helper() + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() error = %v", err) + } + if len(statuses) != total { + t.Fatalf("Status() lists %d migrations, want %d", len(statuses), total) + } + for _, status := range statuses { + if !status.Applied { + t.Fatalf("migration %s is pending", status.Name) + } + } +} + +func assertOutboxTableExists(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool) { + t.Helper() + var exists bool + if err := pool.QueryRow(ctx, `SELECT to_regclass('public.outbox_events') IS NOT NULL`).Scan(&exists); err != nil { + t.Fatalf("check outbox table: %v", err) + } + if exists != want { + t.Fatalf("outbox_events exists = %t, want %t", exists, want) + } +} diff --git a/backend/internal/adapter/secondary/postgres/health.go b/backend/internal/adapter/secondary/postgres/health.go index d8f0377..9a01511 100644 --- a/backend/internal/adapter/secondary/postgres/health.go +++ b/backend/internal/adapter/secondary/postgres/health.go @@ -21,13 +21,9 @@ func NewHealthChecker(ctx context.Context, config config.Config) (*HealthChecker return &HealthChecker{}, func() {}, nil } - poolConfig, err := pgxpool.ParseConfig(config.DatabaseURL) + pool, err := NewPool(ctx, config.DatabaseURL) if err != nil { - return nil, nil, fmt.Errorf("postgres.NewHealthChecker - parse DATABASE_URL: %w", err) - } - pool, err := pgxpool.NewWithConfig(ctx, poolConfig) - if err != nil { - return nil, nil, fmt.Errorf("postgres.NewHealthChecker - create PostgreSQL pool: %w", err) + return nil, nil, fmt.Errorf("postgres.NewHealthChecker - create pool: %w", err) } return &HealthChecker{pool: pool, queries: sqlc.New(pool)}, pool.Close, nil diff --git a/backend/internal/adapter/secondary/postgres/integration_seam.go b/backend/internal/adapter/secondary/postgres/integration_seam.go new file mode 100644 index 0000000..0454d25 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/integration_seam.go @@ -0,0 +1,20 @@ +//go:build integration + +package postgres + +import ( + "github.com/jackc/pgx/v5" + + "lincodex/backend/internal/port/outbound" +) + +// TransactionForIntegrationTest exposes the transaction behind a unit of work +// to integration tests that write test-only tables. It is compiled only with +// the integration build tag and is not part of the adapter API. +func TransactionForIntegrationTest(unit outbound.UnitOfWork) (pgx.Tx, bool) { + postgresUnit, ok := unit.(*UnitOfWork) + if !ok { + return nil, false + } + return postgresUnit.tx, true +} diff --git a/backend/internal/adapter/secondary/postgres/migrator.go b/backend/internal/adapter/secondary/postgres/migrator.go new file mode 100644 index 0000000..a41a688 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/migrator.go @@ -0,0 +1,156 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "io/fs" + "path" + "strconv" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/stdlib" + "github.com/pressly/goose/v3" + "github.com/pressly/goose/v3/lock" +) + +const ( + // The session advisory lock is retried once per second for up to five + // minutes, so instances that start together apply migrations one at a time. + migrationLockRetryPeriodSeconds = 1 + migrationLockRetryAttempts = 300 + + // migrationLockTimeout makes a DDL statement fail fast instead of queueing + // behind long transactions while it blocks every later query on the table. + migrationLockTimeout = 10 * time.Second + // migrationStatementTimeout bounds one migration statement. It stays below + // the five-minute startup limit so a slow statement reports its own error. + migrationStatementTimeout = 4 * time.Minute +) + +// ErrNoMigrationToRollBack reports that no applied migration is left. +var ErrNoMigrationToRollBack = errors.New("no applied migration to roll back") + +// MigrationResult describes one applied or rolled back migration. +type MigrationResult struct { + Version int64 + Name string + Duration time.Duration +} + +// MigrationStatus describes one known migration. +type MigrationStatus struct { + Version int64 + Name string + Applied bool + AppliedAt time.Time +} + +// Migrator applies goose SQL migrations through database/sql with the pgx +// driver. A PostgreSQL session advisory lock serializes concurrent runs. +type Migrator struct { + provider *goose.Provider +} + +// NewMigrator does not connect until a migration operation runs. The caller +// must call Close. +func NewMigrator(databaseURL string, migrations fs.FS) (*Migrator, error) { + connConfig, err := migrationConnConfig(databaseURL) + if err != nil { + return nil, err + } + locker, err := lock.NewPostgresSessionLocker( + lock.WithLockTimeout(migrationLockRetryPeriodSeconds, migrationLockRetryAttempts), + ) + if err != nil { + return nil, fmt.Errorf("postgres.NewMigrator - create session locker: %w", err) + } + database := stdlib.OpenDB(*connConfig) + provider, err := goose.NewProvider(goose.DialectPostgres, database, migrations, + goose.WithSessionLocker(locker), + goose.WithDisableGlobalRegistry(true), + ) + if err != nil { + err = fmt.Errorf("postgres.NewMigrator - load migrations: %w", err) + if closeErr := database.Close(); closeErr != nil { + err = errors.Join(err, fmt.Errorf("postgres.NewMigrator - close migration database: %w", closeErr)) + } + return nil, err + } + return &Migrator{provider: provider}, nil +} + +// migrationConnConfig parses databaseURL and sets session timeouts for every +// migration connection. +func migrationConnConfig(databaseURL string) (*pgx.ConnConfig, error) { + connConfig, err := pgx.ParseConfig(databaseURL) + if err != nil { + // pgx redacts passwords only on a best-effort basis, so the parse error + // is not wrapped to keep the connection string out of logs. + return nil, errors.New("postgres.migrationConnConfig - DATABASE_URL is not a valid PostgreSQL connection string") + } + connConfig.RuntimeParams["lock_timeout"] = strconv.FormatInt(migrationLockTimeout.Milliseconds(), 10) + connConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(migrationStatementTimeout.Milliseconds(), 10) + return connConfig, nil +} + +// Up applies every pending migration and returns them in order. +func (migrator *Migrator) Up(ctx context.Context) ([]MigrationResult, error) { + results, err := migrator.provider.Up(ctx) + if err != nil { + return nil, fmt.Errorf("Migrator.Up - apply migrations: %w", sanitizeConnectError(err)) + } + applied := make([]MigrationResult, 0, len(results)) + for _, result := range results { + applied = append(applied, newMigrationResult(result)) + } + return applied, nil +} + +// DownOne rolls back the most recently applied migration. It returns +// ErrNoMigrationToRollBack when the schema is already at version zero. +func (migrator *Migrator) DownOne(ctx context.Context) (MigrationResult, error) { + result, err := migrator.provider.Down(ctx) + if errors.Is(err, goose.ErrNoNextVersion) { + return MigrationResult{}, fmt.Errorf("Migrator.DownOne - roll back migration: %w", ErrNoMigrationToRollBack) + } + if err != nil { + return MigrationResult{}, fmt.Errorf("Migrator.DownOne - roll back migration: %w", sanitizeConnectError(err)) + } + return newMigrationResult(result), nil +} + +// Status lists every embedded migration with its database state. +func (migrator *Migrator) Status(ctx context.Context) ([]MigrationStatus, error) { + statuses, err := migrator.provider.Status(ctx) + if err != nil { + return nil, fmt.Errorf("Migrator.Status - read migration status: %w", sanitizeConnectError(err)) + } + result := make([]MigrationStatus, 0, len(statuses)) + for _, status := range statuses { + result = append(result, MigrationStatus{ + Version: status.Source.Version, + Name: path.Base(status.Source.Path), + Applied: status.State == goose.StateApplied, + AppliedAt: status.AppliedAt, + }) + } + return result, nil +} + +// Close releases the migration connections. +func (migrator *Migrator) Close() error { + if err := migrator.provider.Close(); err != nil { + return fmt.Errorf("Migrator.Close - close migration database: %w", err) + } + return nil +} + +func newMigrationResult(result *goose.MigrationResult) MigrationResult { + return MigrationResult{ + Version: result.Source.Version, + Name: path.Base(result.Source.Path), + Duration: result.Duration, + } +} diff --git a/backend/internal/adapter/secondary/postgres/migrator_test.go b/backend/internal/adapter/secondary/postgres/migrator_test.go new file mode 100644 index 0000000..d054c9e --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/migrator_test.go @@ -0,0 +1,94 @@ +package postgres + +import ( + "errors" + "strings" + "testing" + "testing/fstest" + "time" + + "github.com/jackc/pgx/v5/pgconn" + + "lincodex/backend/db" +) + +// unreachableDatabaseURL points at a closed local port. The tests below never +// need a server: constructors do not connect, and the connect test expects a +// refusal. +const unreachableDatabaseURL = "postgres://migrator:migration-secret@127.0.0.1:1/app?sslmode=disable&connect_timeout=2" + +func TestNewMigratorLoadsEmbeddedMigrationsWithoutConnecting(t *testing.T) { + migrations, err := db.Migrations() + if err != nil { + t.Fatalf("db.Migrations() error = %v", err) + } + migrator, err := NewMigrator(unreachableDatabaseURL, migrations) + if err != nil { + t.Fatalf("NewMigrator() rejected the embedded migrations: %v", err) + } + if err := migrator.Close(); err != nil { + t.Fatalf("Close() error = %v", err) + } +} + +func TestNewMigratorRejectsDuplicateVersions(t *testing.T) { + migrations := fstest.MapFS{ + "00001_first.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n-- +goose Down\nSELECT 1;\n")}, + "00001_second.sql": {Data: []byte("-- +goose Up\nSELECT 1;\n-- +goose Down\nSELECT 1;\n")}, + } + if migrator, err := NewMigrator(unreachableDatabaseURL, migrations); err == nil { + _ = migrator.Close() + t.Fatal("NewMigrator() accepted two migrations with the same version") + } +} + +func TestMigrationConnConfigSetsSessionTimeouts(t *testing.T) { + connConfig, err := migrationConnConfig(unreachableDatabaseURL) + if err != nil { + t.Fatalf("migrationConnConfig() error = %v", err) + } + for name, want := range map[string]time.Duration{ + "lock_timeout": migrationLockTimeout, + "statement_timeout": migrationStatementTimeout, + } { + got, err := time.ParseDuration(connConfig.RuntimeParams[name] + "ms") + if err != nil || got != want { + t.Fatalf("%s = %q, want %s", name, connConfig.RuntimeParams[name], want) + } + } +} + +func TestMigrationConnConfigHidesInvalidURL(t *testing.T) { + const password = "parse-secret" + _, err := migrationConnConfig("postgres://app:" + password + "@db:not-a-port/app") + if err == nil { + t.Fatal("migrationConnConfig() accepted an invalid URL") + } + if strings.Contains(err.Error(), password) { + t.Fatalf("migrationConnConfig() error exposes the password: %v", err) + } +} + +func TestSanitizeConnectErrorDropsConnectionIdentity(t *testing.T) { + _, connectErr := pgconn.Connect(t.Context(), unreachableDatabaseURL) + var original *pgconn.ConnectError + if !errors.As(connectErr, &original) { + t.Fatalf("pgconn.Connect() error = %v, want *pgconn.ConnectError", connectErr) + } + err := sanitizeConnectError(connectErr) + for _, secret := range []string{"user=", "migrator", "migration-secret", "database=app"} { + if strings.Contains(err.Error(), secret) { + t.Fatalf("sanitizeConnectError() = %v, still contains %q", err, secret) + } + } + if !errors.Is(err, original.Unwrap()) { + t.Fatalf("sanitizeConnectError() = %v, lost the network cause", err) + } +} + +func TestSanitizeConnectErrorKeepsOtherErrors(t *testing.T) { + original := errors.New("relation does not exist") + if err := sanitizeConnectError(original); err != original { //nolint:errorlint // Identity is the property under test. + t.Fatalf("sanitizeConnectError() = %v, want the original error", err) + } +} diff --git a/backend/internal/adapter/secondary/postgres/outbox.go b/backend/internal/adapter/secondary/postgres/outbox.go new file mode 100644 index 0000000..ae372af --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/outbox.go @@ -0,0 +1,63 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + uniqueViolationCode = "23505" + + outboxPrimaryKeyConstraint = "outbox_events_pkey" + outboxAggregateVersionConstraint = "outbox_events_aggregate_version_event_type_key" +) + +type outboxWriter struct { + queries *sqlc.Queries +} + +func (writer outboxWriter) Append(ctx context.Context, events ...domain.DomainEvent) error { + for _, event := range events { + if event.EventID() == uuid.Nil { + return fmt.Errorf("outboxWriter.Append - event was not built by domain.NewDomainEvent: %w", domain.ErrInvalidDomainEvent) + } + err := writer.queries.InsertOutboxEvent(ctx, sqlc.InsertOutboxEventParams{ + EventID: pgtype.UUID{Bytes: event.EventID(), Valid: true}, + EventType: event.EventType(), + SchemaVersion: event.SchemaVersion(), + AggregateType: event.AggregateType(), + AggregateID: pgtype.UUID{Bytes: event.AggregateID(), Valid: true}, + AggregateVersion: event.AggregateVersion(), + Payload: event.Payload(), + }) + if err != nil { + return fmt.Errorf("outboxWriter.Append - insert outbox event: %w", mapOutboxError(err)) + } + } + return nil +} + +// mapOutboxError turns outbox uniqueness violations into a port sentinel that +// keeps the constraint name. Other errors pass through; PostgreSQL error text +// does not include key values. +func mapOutboxError(err error) error { + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != uniqueViolationCode { + return err + } + switch pgError.ConstraintName { + case outboxPrimaryKeyConstraint, outboxAggregateVersionConstraint: + return fmt.Errorf("postgres.mapOutboxError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrOutboxEventConflict) + default: + return err + } +} diff --git a/backend/internal/adapter/secondary/postgres/outbox_test.go b/backend/internal/adapter/secondary/postgres/outbox_test.go new file mode 100644 index 0000000..52cf89a --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/outbox_test.go @@ -0,0 +1,45 @@ +package postgres + +import ( + "errors" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgconn" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestMapOutboxErrorRecognizesOutboxConflicts(t *testing.T) { + for _, constraint := range []string{outboxPrimaryKeyConstraint, outboxAggregateVersionConstraint} { + err := mapOutboxError(&pgconn.PgError{Code: uniqueViolationCode, ConstraintName: constraint}) + if !errors.Is(err, outbound.ErrOutboxEventConflict) { + t.Fatalf("mapOutboxError(%s) = %v, want ErrOutboxEventConflict", constraint, err) + } + if !strings.Contains(err.Error(), constraint) { + t.Fatalf("mapOutboxError(%s) = %v, want the constraint name in the message", constraint, err) + } + } +} + +func TestMapOutboxErrorKeepsOtherErrors(t *testing.T) { + tests := []error{ + &pgconn.PgError{Code: uniqueViolationCode, ConstraintName: "other_table_key"}, + &pgconn.PgError{Code: "23514", ConstraintName: "outbox_events_schema_version_positive"}, + errors.New("connection reset"), + } + for _, original := range tests { + if err := mapOutboxError(original); err != original { //nolint:errorlint // Identity is the property under test. + t.Fatalf("mapOutboxError(%v) = %v, want the original error", original, err) + } + } +} + +func TestAppendRejectsZeroValueEventBeforeTheDatabase(t *testing.T) { + // A nil query set proves that validation happens before any statement. + err := outboxWriter{}.Append(t.Context(), domain.DomainEvent{}) + if !errors.Is(err, domain.ErrInvalidDomainEvent) { + t.Fatalf("Append() error = %v, want ErrInvalidDomainEvent", err) + } +} diff --git a/backend/internal/adapter/secondary/postgres/pool.go b/backend/internal/adapter/secondary/postgres/pool.go new file mode 100644 index 0000000..07b0b97 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/pool.go @@ -0,0 +1,42 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" +) + +// NewPool creates a connection pool without opening a connection; the pool +// connects lazily on first use, so constructing it never waits for the +// database. Startup migrations, not the pool, decide whether the service +// requires the database before serving. The caller owns the pool and must +// close it. +func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) { + poolConfig, err := pgxpool.ParseConfig(databaseURL) + if err != nil { + // pgx redacts passwords only on a best-effort basis, so the parse error + // is not wrapped to keep the connection string out of logs. + return nil, errors.New("postgres.NewPool - DATABASE_URL is not a valid PostgreSQL connection string") + } + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + return nil, fmt.Errorf("postgres.NewPool - create PostgreSQL pool: %w", err) + } + return pool, nil +} + +// sanitizeConnectError drops the pgx connection prefix, which names the +// database user and database, while keeping the network or server cause. +func sanitizeConnectError(err error) error { + var connectError *pgconn.ConnectError + if !errors.As(err, &connectError) { + return err + } + if cause := connectError.Unwrap(); cause != nil { + return fmt.Errorf("postgres.sanitizeConnectError - connect to PostgreSQL: %w", cause) + } + return errors.New("postgres.sanitizeConnectError - connect to PostgreSQL failed") +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 576325d..8c2fcaf 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -3,3 +3,20 @@ // sqlc v1.31.1 package sqlc + +import ( + "github.com/jackc/pgx/v5/pgtype" +) + +type OutboxEvent struct { + Position pgtype.Int8 + EventID pgtype.UUID + EventType string + SchemaVersion int32 + AggregateType string + AggregateID pgtype.UUID + AggregateVersion int64 + Payload []byte + OccurredAt pgtype.Timestamptz + PublishedAt pgtype.Timestamptz +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/outbox.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/outbox.sql.go new file mode 100644 index 0000000..fb8dcc9 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/outbox.sql.go @@ -0,0 +1,55 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: outbox.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const insertOutboxEvent = `-- name: InsertOutboxEvent :exec +INSERT INTO outbox_events ( + event_id, + event_type, + schema_version, + aggregate_type, + aggregate_id, + aggregate_version, + payload +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7 +) +` + +type InsertOutboxEventParams struct { + EventID pgtype.UUID + EventType string + SchemaVersion int32 + AggregateType string + AggregateID pgtype.UUID + AggregateVersion int64 + Payload []byte +} + +func (q *Queries) InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error { + _, err := q.db.Exec(ctx, insertOutboxEvent, + arg.EventID, + arg.EventType, + arg.SchemaVersion, + arg.AggregateType, + arg.AggregateID, + arg.AggregateVersion, + arg.Payload, + ) + return err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index b9a2e69..c508693 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -9,6 +9,7 @@ import ( ) type Querier interface { + InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error Ping(ctx context.Context) (int32, error) } diff --git a/backend/internal/adapter/secondary/postgres/transactor.go b/backend/internal/adapter/secondary/postgres/transactor.go new file mode 100644 index 0000000..6d215ff --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/transactor.go @@ -0,0 +1,104 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/port/outbound" +) + +// rollbackTimeout bounds a rollback that runs after the caller's context may +// already be canceled. +const rollbackTimeout = 5 * time.Second + +// transactionOptions selects READ COMMITTED explicitly. Outbox writes are +// inserts guarded by unique constraints, and aggregate updates are expected to +// use optimistic version checks in their WHERE clause, so stricter isolation +// would only add serialization retries to every caller. A usecase that needs +// SERIALIZABLE should get an explicit option rather than a silent default. +var transactionOptions = pgx.TxOptions{ + IsoLevel: pgx.ReadCommitted, + AccessMode: pgx.ReadWrite, +} + +// Transactor implements outbound.Transactor with a pgx pool owned by the caller. +type Transactor struct { + pool *pgxpool.Pool +} + +func NewTransactor(pool *pgxpool.Pool) *Transactor { + return &Transactor{pool: pool} +} + +var _ outbound.Transactor = (*Transactor)(nil) + +// transactionContextKey marks a context passed to a transaction callback so a +// nested WithinTransaction call fails instead of opening a second connection. +type transactionContextKey struct{} + +func (transactor *Transactor) WithinTransaction( + ctx context.Context, + fn func(ctx context.Context, unit outbound.UnitOfWork) error, +) error { + if ctx.Value(transactionContextKey{}) != nil { + return fmt.Errorf("Transactor.WithinTransaction - begin transaction: %w", outbound.ErrNestedTransaction) + } + tx, err := transactor.pool.BeginTx(ctx, transactionOptions) + if err != nil { + return fmt.Errorf("Transactor.WithinTransaction - begin transaction: %w", sanitizeConnectError(err)) + } + finished := false + defer func() { + // Runs only when fn panics or calls runtime.Goexit. Not recovering + // keeps the original panic and its stack; the rollback error cannot + // change that outcome. + if !finished { + _ = rollback(ctx, tx) + } + }() + + fnErr := fn(context.WithValue(ctx, transactionContextKey{}, true), &UnitOfWork{tx: tx, queries: sqlc.New(tx)}) + finished = true + if fnErr != nil { + if rollbackErr := rollback(ctx, tx); rollbackErr != nil { + return errors.Join(fnErr, fmt.Errorf("Transactor.WithinTransaction - roll back transaction: %w", rollbackErr)) + } + return fnErr + } + if err := tx.Commit(ctx); err != nil { + // pgx reports pgx.ErrTxCommitRollback when fn ignored a statement error + // and PostgreSQL rolled the aborted transaction back instead. After a + // network error the commit outcome is unknown; see outbound.Transactor. + return fmt.Errorf("Transactor.WithinTransaction - commit transaction: %w", err) + } + return nil +} + +func rollback(ctx context.Context, tx pgx.Tx) error { + rollbackContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), rollbackTimeout) + defer cancel() + if err := tx.Rollback(rollbackContext); err != nil && !errors.Is(err, pgx.ErrTxClosed) { + return fmt.Errorf("postgres.rollback - roll back: %w", err) + } + return nil +} + +// UnitOfWork binds repositories to one transaction. Repositories in this +// adapter use tx directly; usecases depend on outbound.UnitOfWork and never +// see pgx types. +type UnitOfWork struct { + tx pgx.Tx + queries *sqlc.Queries +} + +var _ outbound.UnitOfWork = (*UnitOfWork)(nil) + +func (unit *UnitOfWork) Outbox() outbound.OutboxWriter { + return outboxWriter{queries: unit.queries} +} diff --git a/backend/internal/bootstrap/app.go b/backend/internal/bootstrap/app.go index db6adc2..3356404 100644 --- a/backend/internal/bootstrap/app.go +++ b/backend/internal/bootstrap/app.go @@ -72,6 +72,9 @@ func run(ctx context.Context, config config.Config, logger *slog.Logger) error { if err := config.Validate(); err != nil { return fmt.Errorf("bootstrap.run - validate configuration: %w", err) } + if err := migrateDatabase(ctx, config, logger); err != nil { + return fmt.Errorf("bootstrap.run - migrate database: %w", err) + } application, cleanup, err := initialize(ctx, config, logger) if err != nil { return fmt.Errorf("bootstrap.run - initialize application: %w", err) diff --git a/backend/internal/bootstrap/app_test.go b/backend/internal/bootstrap/app_test.go index 3c6c2ba..a62b49e 100644 --- a/backend/internal/bootstrap/app_test.go +++ b/backend/internal/bootstrap/app_test.go @@ -3,11 +3,14 @@ package bootstrap import ( "context" "errors" + "log/slog" "net" "net/http" "strings" "testing" "time" + + "lincodex/backend/config" ) func TestServeServersGracefullyStopsOnCancellation(t *testing.T) { @@ -67,3 +70,35 @@ func listenForTest(t *testing.T) net.Listener { t.Cleanup(func() { _ = listener.Close() }) return listener } + +func TestMigrateDatabaseSkipsWithoutWork(t *testing.T) { + tests := []struct { + name string + settings config.Config + }{ + {name: "disabled", settings: config.Config{DatabaseMigrateOnStart: false, DatabaseURL: "postgres://app@db/app"}}, + {name: "database not configured", settings: config.Config{DatabaseMigrateOnStart: true}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if err := migrateDatabase(t.Context(), test.settings, slog.New(slog.DiscardHandler)); err != nil { + t.Fatalf("migrateDatabase() error = %v", err) + } + }) + } +} + +func TestMigrateDatabaseHidesConnectionStringOnFailure(t *testing.T) { + const password = "startup-secret-password" + settings := config.Config{ + DatabaseMigrateOnStart: true, + DatabaseURL: "postgres://app:" + password + "@db:not-a-port/app", + } + err := migrateDatabase(t.Context(), settings, slog.New(slog.DiscardHandler)) + if err == nil { + t.Fatal("migrateDatabase() accepted an invalid DATABASE_URL") + } + if strings.Contains(err.Error(), password) || strings.Contains(err.Error(), "db:not-a-port") { + t.Fatalf("migrateDatabase() error exposes the connection string: %v", err) + } +} diff --git a/backend/internal/bootstrap/migrate.go b/backend/internal/bootstrap/migrate.go new file mode 100644 index 0000000..84eb989 --- /dev/null +++ b/backend/internal/bootstrap/migrate.go @@ -0,0 +1,57 @@ +package bootstrap + +import ( + "context" + "errors" + "fmt" + "log/slog" + "time" + + "lincodex/backend/config" + "lincodex/backend/db" + "lincodex/backend/internal/adapter/secondary/postgres" +) + +// startupMigrationTimeout bounds lock waiting and migration work before the +// servers start. It matches the migration lock retry window. +const startupMigrationTimeout = 5 * time.Minute + +// migrateDatabase applies embedded migrations before any listener opens, so the +// service never serves requests against an older schema. Without DATABASE_URL +// the service keeps its existing behavior: it starts and reports not ready. +func migrateDatabase(ctx context.Context, settings config.Config, logger *slog.Logger) error { + if !settings.DatabaseMigrateOnStart { + logger.Info("startup database migrations are disabled") + return nil + } + if settings.DatabaseURL == "" { + logger.Warn("startup database migrations skipped because DATABASE_URL is not set") + return nil + } + migrations, err := db.Migrations() + if err != nil { + return fmt.Errorf("bootstrap.migrateDatabase - load migrations: %w", err) + } + migrator, err := postgres.NewMigrator(settings.DatabaseURL, migrations) + if err != nil { + return fmt.Errorf("bootstrap.migrateDatabase - create migrator: %w", err) + } + ctx, cancel := context.WithTimeout(ctx, startupMigrationTimeout) + defer cancel() + applied, err := migrator.Up(ctx) + if closeErr := migrator.Close(); closeErr != nil { + err = errors.Join(err, fmt.Errorf("bootstrap.migrateDatabase - close migrator: %w", closeErr)) + } + if err != nil { + return fmt.Errorf("bootstrap.migrateDatabase - apply migrations: %w", err) + } + for _, migration := range applied { + logger.Info("database migration applied", + slog.Int64("version", migration.Version), + slog.String("name", migration.Name), + slog.Duration("duration", migration.Duration), + ) + } + logger.Info("database schema is up to date", slog.Int("applied_migrations", len(applied))) + return nil +} diff --git a/backend/internal/domain/.gitkeep b/backend/internal/domain/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/backend/internal/domain/domain_event.go b/backend/internal/domain/domain_event.go new file mode 100644 index 0000000..0f8188a --- /dev/null +++ b/backend/internal/domain/domain_event.go @@ -0,0 +1,183 @@ +package domain + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "regexp" + "strings" + "unicode/utf8" + + "github.com/google/uuid" +) + +const ( + // MaxDomainEventPayloadBytes bounds the compact JSON payload. Events carry + // identifiers and minimal facts; larger data stays in the source tables. + MaxDomainEventPayloadBytes = 16 << 10 + maxDomainEventTypeLength = 128 + maxAggregateTypeLength = 64 + // maxDomainEventPayloadDepth bounds object and array nesting. Minimal facts + // do not need deep structures, and the bound keeps decoding cheap. + maxDomainEventPayloadDepth = 32 +) + +var ( + ErrInvalidDomainEvent = errors.New("invalid domain event") + + // Lowercase dotted names such as "identity.user_registered". + domainEventTypePattern = regexp.MustCompile(`^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$`) + // Lowercase snake_case names such as "user" or "company_member". + aggregateTypePattern = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) +) + +// DomainEvent is an immutable fact about one aggregate version, recorded in the +// transactional outbox and later published to the event bus. +// +// The payload must carry identifiers and minimal facts only. It must never +// contain contact data, tokens, passwords, document contents, or other personal +// data that a consumer can read from the source of truth under its own access +// rules. +// +// The outbox stores the payload as jsonb, which normalizes it: key order and +// whitespace change and duplicate keys keep the last value. Consumers must +// compare payloads as JSON values, not bytes. +type DomainEvent struct { + eventID uuid.UUID + eventType string + schemaVersion int32 + aggregateType string + aggregateID uuid.UUID + aggregateVersion int64 + payload []byte +} + +// DomainEventInput describes a new event. Payload must be a JSON object of at +// most MaxDomainEventPayloadBytes in compact form, nested at most 32 levels, +// with numbers in float64 range and no NUL characters, which jsonb cannot +// store. +type DomainEventInput struct { + EventType string + SchemaVersion int32 + AggregateType string + AggregateID uuid.UUID + AggregateVersion int64 + Payload []byte +} + +// NewDomainEvent validates input and assigns a time-ordered UUIDv7 event ID. +// The stored payload is the compact form of input.Payload. +func NewDomainEvent(input DomainEventInput) (DomainEvent, error) { + if err := input.validateIdentity(); err != nil { + return DomainEvent{}, err + } + payload, err := compactPayload(input.Payload) + if err != nil { + return DomainEvent{}, err + } + eventID, err := uuid.NewV7() + if err != nil { + return DomainEvent{}, fmt.Errorf("domain.NewDomainEvent - generate event ID: %w", err) + } + return DomainEvent{ + eventID: eventID, + eventType: input.EventType, + schemaVersion: input.SchemaVersion, + aggregateType: input.AggregateType, + aggregateID: input.AggregateID, + aggregateVersion: input.AggregateVersion, + payload: payload, + }, nil +} + +func (input DomainEventInput) validateIdentity() error { + if len(input.EventType) > maxDomainEventTypeLength || !domainEventTypePattern.MatchString(input.EventType) { + return invalidDomainEvent("event type must be a lowercase dotted name of at most 128 bytes") + } + if input.SchemaVersion <= 0 { + return invalidDomainEvent("schema version must be positive") + } + if len(input.AggregateType) > maxAggregateTypeLength || !aggregateTypePattern.MatchString(input.AggregateType) { + return invalidDomainEvent("aggregate type must be a lowercase snake_case name of at most 64 bytes") + } + if input.AggregateID == uuid.Nil { + return invalidDomainEvent("aggregate ID must not be nil") + } + if input.AggregateVersion <= 0 { + return invalidDomainEvent("aggregate version must be positive") + } + return nil +} + +func compactPayload(payload []byte) ([]byte, error) { + // encoding/json accepts invalid UTF-8 inside strings; PostgreSQL does not. + if !utf8.Valid(payload) { + return nil, invalidDomainEvent("payload must be valid UTF-8") + } + var compact bytes.Buffer + if err := json.Compact(&compact, payload); err != nil { + return nil, invalidDomainEvent("payload must be valid JSON") + } + if compact.Len() == 0 || compact.Bytes()[0] != '{' { + return nil, invalidDomainEvent("payload must be a JSON object") + } + if compact.Len() > MaxDomainEventPayloadBytes { + return nil, invalidDomainEvent("payload exceeds 16 KiB") + } + var decoded any + if err := json.Unmarshal(compact.Bytes(), &decoded); err != nil { + // Compact already checked the syntax, so this is a number outside the + // float64 range. + return nil, invalidDomainEvent("payload numbers must fit a float64") + } + if err := checkPayloadValue(decoded, 1); err != nil { + return nil, err + } + return compact.Bytes(), nil +} + +// checkPayloadValue rejects values that PostgreSQL jsonb cannot store and +// nesting deeper than maxDomainEventPayloadDepth. +func checkPayloadValue(value any, depth int) error { + switch typed := value.(type) { + case map[string]any: + if depth > maxDomainEventPayloadDepth { + return invalidDomainEvent("payload nesting exceeds 32 levels") + } + for key, item := range typed { + if strings.ContainsRune(key, 0) { + return invalidDomainEvent("payload must not contain NUL characters") + } + if err := checkPayloadValue(item, depth+1); err != nil { + return err + } + } + case []any: + if depth > maxDomainEventPayloadDepth { + return invalidDomainEvent("payload nesting exceeds 32 levels") + } + for _, item := range typed { + if err := checkPayloadValue(item, depth+1); err != nil { + return err + } + } + case string: + if strings.ContainsRune(typed, 0) { + return invalidDomainEvent("payload must not contain NUL characters") + } + } + return nil +} + +func invalidDomainEvent(reason string) error { + return fmt.Errorf("domain.NewDomainEvent - %s: %w", reason, ErrInvalidDomainEvent) +} + +func (event DomainEvent) EventID() uuid.UUID { return event.eventID } +func (event DomainEvent) EventType() string { return event.eventType } +func (event DomainEvent) SchemaVersion() int32 { return event.schemaVersion } +func (event DomainEvent) AggregateType() string { return event.aggregateType } +func (event DomainEvent) AggregateID() uuid.UUID { return event.aggregateID } +func (event DomainEvent) AggregateVersion() int64 { return event.aggregateVersion } +func (event DomainEvent) Payload() json.RawMessage { return bytes.Clone(event.payload) } diff --git a/backend/internal/domain/domain_event_test.go b/backend/internal/domain/domain_event_test.go new file mode 100644 index 0000000..813e866 --- /dev/null +++ b/backend/internal/domain/domain_event_test.go @@ -0,0 +1,138 @@ +package domain + +import ( + "bytes" + "errors" + "strings" + "testing" + + "github.com/google/uuid" +) + +func validDomainEventInput() DomainEventInput { + return DomainEventInput{ + EventType: "identity.user_registered", + SchemaVersion: 1, + AggregateType: "user", + AggregateID: uuid.MustParse("0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d"), + AggregateVersion: 1, + Payload: []byte(` { "user_id" : "0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d" } `), + } +} + +func TestNewDomainEventAcceptsValidInput(t *testing.T) { + input := validDomainEventInput() + event, err := NewDomainEvent(input) + if err != nil { + t.Fatalf("NewDomainEvent() error = %v", err) + } + if event.EventID().Version() != 7 { + t.Fatalf("EventID version = %d, want UUIDv7", event.EventID().Version()) + } + if event.EventType() != input.EventType || event.SchemaVersion() != input.SchemaVersion || + event.AggregateType() != input.AggregateType || event.AggregateID() != input.AggregateID || + event.AggregateVersion() != input.AggregateVersion { + t.Fatalf("NewDomainEvent() did not preserve identity fields: %+v", event) + } + if want := `{"user_id":"0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d"}`; string(event.Payload()) != want { + t.Fatalf("Payload() = %s, want compact %s", event.Payload(), want) + } + event.Payload()[0] = '[' + if event.Payload()[0] != '{' { + t.Fatal("Payload() exposed the event's internal buffer") + } + + other, err := NewDomainEvent(input) + if err != nil { + t.Fatalf("NewDomainEvent() error = %v", err) + } + if other.EventID() == event.EventID() { + t.Fatal("NewDomainEvent() reused an event ID") + } +} + +func TestNewDomainEventAcceptsPayloadAtSizeLimit(t *testing.T) { + input := validDomainEventInput() + prefix, suffix := `{"padding":"`, `"}` + input.Payload = []byte(prefix + strings.Repeat("a", MaxDomainEventPayloadBytes-len(prefix)-len(suffix)) + suffix) + if _, err := NewDomainEvent(input); err != nil { + t.Fatalf("NewDomainEvent() rejected a payload at the limit: %v", err) + } +} + +func TestNewDomainEventRejectsInvalidInput(t *testing.T) { + prefix, suffix := `{"padding":"`, `"}` + oversized := prefix + strings.Repeat("a", MaxDomainEventPayloadBytes-len(prefix)-len(suffix)+1) + suffix + tests := []struct { + name string + change func(*DomainEventInput) + }{ + {name: "empty event type", change: func(input *DomainEventInput) { input.EventType = "" }}, + {name: "event type without namespace", change: func(input *DomainEventInput) { input.EventType = "registered" }}, + {name: "uppercase event type", change: func(input *DomainEventInput) { input.EventType = "Identity.UserRegistered" }}, + {name: "long event type", change: func(input *DomainEventInput) { input.EventType = "a." + strings.Repeat("b", 127) }}, + {name: "zero schema version", change: func(input *DomainEventInput) { input.SchemaVersion = 0 }}, + {name: "negative schema version", change: func(input *DomainEventInput) { input.SchemaVersion = -1 }}, + {name: "empty aggregate type", change: func(input *DomainEventInput) { input.AggregateType = "" }}, + {name: "dotted aggregate type", change: func(input *DomainEventInput) { input.AggregateType = "identity.user" }}, + {name: "long aggregate type", change: func(input *DomainEventInput) { input.AggregateType = strings.Repeat("a", 65) }}, + {name: "nil aggregate ID", change: func(input *DomainEventInput) { input.AggregateID = uuid.Nil }}, + {name: "zero aggregate version", change: func(input *DomainEventInput) { input.AggregateVersion = 0 }}, + {name: "negative aggregate version", change: func(input *DomainEventInput) { input.AggregateVersion = -1 }}, + {name: "empty payload", change: func(input *DomainEventInput) { input.Payload = nil }}, + {name: "invalid JSON payload", change: func(input *DomainEventInput) { input.Payload = []byte(`{"user_id":`) }}, + {name: "array payload", change: func(input *DomainEventInput) { input.Payload = []byte(`[1]`) }}, + {name: "null payload", change: func(input *DomainEventInput) { input.Payload = []byte(`null`) }}, + {name: "invalid UTF-8 payload", change: func(input *DomainEventInput) { input.Payload = []byte("{\"a\":\"\xff\"}") }}, + {name: "escaped NUL in value", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":"x\u0000y"}`) }}, + {name: "escaped NUL in key", change: func(input *DomainEventInput) { input.Payload = []byte(`{"\u0000":1}`) }}, + {name: "escaped NUL in nested array", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":[{"b":"\u0000"}]}`) }}, + {name: "number outside float64 range", change: func(input *DomainEventInput) { input.Payload = []byte(`{"a":1e400}`) }}, + {name: "nesting too deep", change: func(input *DomainEventInput) { input.Payload = nestedPayload(maxDomainEventPayloadDepth + 1) }}, + {name: "oversized payload", change: func(input *DomainEventInput) { input.Payload = []byte(oversized) }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + input := validDomainEventInput() + test.change(&input) + _, err := NewDomainEvent(input) + if !errors.Is(err, ErrInvalidDomainEvent) { + t.Fatalf("NewDomainEvent() error = %v, want ErrInvalidDomainEvent", err) + } + }) + } +} + +func TestNewDomainEventDoesNotKeepCallerPayload(t *testing.T) { + input := validDomainEventInput() + input.Payload = []byte(`{"a":1}`) + event, err := NewDomainEvent(input) + if err != nil { + t.Fatalf("NewDomainEvent() error = %v", err) + } + copy(input.Payload, `{"b":2}`) + if !bytes.Equal(event.Payload(), []byte(`{"a":1}`)) { + t.Fatalf("Payload() = %s, changed with the caller's buffer", event.Payload()) + } +} + +func TestNewDomainEventAcceptsEdgePayloads(t *testing.T) { + for name, payload := range map[string][]byte{ + "escaped backslash before u0000 text": []byte(`{"a":"\\u0000"}`), + "maximum nesting": nestedPayload(maxDomainEventPayloadDepth), + "large integer": []byte(`{"a":123456789012345678901234567890}`), + } { + t.Run(name, func(t *testing.T) { + input := validDomainEventInput() + input.Payload = payload + if _, err := NewDomainEvent(input); err != nil { + t.Fatalf("NewDomainEvent() error = %v", err) + } + }) + } +} + +// nestedPayload returns an object whose containers nest depth levels deep. +func nestedPayload(depth int) []byte { + return []byte(strings.Repeat(`{"a":`, depth) + "1" + strings.Repeat("}", depth)) +} diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go new file mode 100644 index 0000000..34f69b6 --- /dev/null +++ b/backend/internal/port/outbound/transaction.go @@ -0,0 +1,57 @@ +package outbound + +import ( + "context" + "errors" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrOutboxEventConflict reports that the event ID, or the same event type + // for the same aggregate version, is already recorded. The surrounding + // transaction is aborted and rolled back. + ErrOutboxEventConflict = errors.New("outbox event already recorded") + + // ErrNestedTransaction reports a WithinTransaction call from inside another + // transaction callback. Nested calls would silently use a second connection + // and commit independently of the outer transaction. + ErrNestedTransaction = errors.New("transaction already in progress") +) + +// Transactor runs a business operation in one database transaction. +type Transactor interface { + // WithinTransaction commits when fn returns nil and rolls back when fn + // returns an error or panics. The error is returned unchanged in identity + // and a panic is re-raised after the rollback. fn must use only the + // UnitOfWork and context it receives and must not retain them after + // returning. Calling WithinTransaction with that context returns + // ErrNestedTransaction. After a database error inside fn the transaction is + // aborted, so fn should return that error. + // + // A network failure during commit leaves the outcome unknown: the + // transaction may or may not have committed. Callers that retry must make + // the operation idempotent, for example through aggregate version checks + // and the outbox uniqueness rules. + WithinTransaction(ctx context.Context, fn func(ctx context.Context, unit UnitOfWork) error) error +} + +// UnitOfWork exposes repositories bound to one transaction. Product +// repositories are added here as their usecases appear. +type UnitOfWork interface { + Outbox() OutboxWriter +} + +// OutboxWriter appends domain events to the transactional outbox. Events become +// visible to the relay only after the surrounding transaction commits. +// +// The outbox rejects a second event of the same type for the same aggregate +// version. That rule is a backstop, not concurrency control: aggregate updates +// must still check the expected version (UPDATE ... WHERE version = $n) so a +// stale writer fails before it records an event. +type OutboxWriter interface { + // Append returns an error wrapping ErrOutboxEventConflict for a duplicate + // and domain.ErrInvalidDomainEvent for an event not built by + // domain.NewDomainEvent. + Append(ctx context.Context, events ...domain.DomainEvent) error +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 95000d7..e94302e 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -44,13 +44,38 @@ The planned backend boundaries are: Shared Go configuration belongs in backend/config/ outside internal. wahrwelt-kit logkit 0.6.0, httpkit 0.7.0, and cachekit 0.7.0 currently provide technical functions. Metrics use bounded custom collector/middleware code, and pgxpool collection must not block startup. pgkit and httpkit/metrics are not currently used. Technical libraries do not own product rules. Do not add unselected JWT or WebSocket dependencies for hypothetical features. -PostgreSQL with pgx, sqlc, and goose remains the planned database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment. +PostgreSQL with pgx, sqlc, and goose is the database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations: the SQL files are embedded in the binary, and the backend applies them at startup under a PostgreSQL advisory lock before it opens its listeners. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment. Redis is part of the core Compose project and connects through `backend/internal/adapter/secondary/redis/` to the outbound cache port. The adapter provides Get/Set/Del with TTL; bootstrap manages client construction and cleanup. The internal /readyz requires PostgreSQL, Redis, and the SeaweedFS bucket to be available. The cache is not a source of truth: future consumers must tolerate key eviction and Redis restarts. Profile, search, resume, and other product caching rules are not implemented yet. SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. Resume uploads, authorization, content limits, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup. -The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, while the Go client, outbox, and relay are not implemented yet. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help. +The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node and the `outbox_events` table with its transactional writer exists, while the Go Kafka client and the relay are not implemented yet. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help. + +### Transactional outbox + +Implemented: migration `backend/db/migrations/00001_create_outbox_events.sql` creates `outbox_events`. Columns: + +- `position`: a bigint identity, unique and monotonic in insertion order; the relay scans by it. +- `event_id`: uuid primary key, a UUIDv7 generated in Go. +- `event_type`: a lowercase dotted name of at most 128 bytes. +- `schema_version`: an integer above zero. +- `aggregate_type`: snake_case, at most 64 bytes. +- `aggregate_id`: a uuid. +- `aggregate_version`: a bigint above zero. +- `payload`: a jsonb object. +- `occurred_at`: `clock_timestamp()` at insert. It is informational only and does not define order. +- `published_at`: null until the relay publishes the row. + +A unique key on aggregate type, aggregate ID, aggregate version, and event type rejects a second event of the same type for the same aggregate version. A partial index on `position` where `published_at` is null serves the relay scan. CHECK constraints repeat the domain rules for versions, names, and the object payload as a backstop. The payload size limit lives only in Go, because the jsonb text and binary sizes differ from the compact input and a database length check could reject an event the domain accepted. + +A usecase writes through outbound ports. `Transactor.WithinTransaction(ctx, fn)` opens one READ COMMITTED transaction and passes a `UnitOfWork`; every repository it returns, including `Outbox().Append(ctx, events...)`, uses that transaction. The transaction commits when fn returns nil and rolls back when fn returns an error, panics, or its context is canceled. Calling `WithinTransaction` again with the callback context returns `outbound.ErrNestedTransaction` instead of opening a second connection. A conflict on the event ID or the unique key returns an error that wraps `outbound.ErrOutboxEventConflict` and names the constraint. A network error during commit leaves the outcome unknown, so callers that retry must be idempotent. + +The outbox uniqueness rule is a backstop, not concurrency control. Aggregate updates still check the expected version (`UPDATE ... WHERE version = $n`), so a stale writer fails before it records an event. + +`domain.NewDomainEvent` validates the event. The compact JSON payload is limited to 16 KiB and 32 nesting levels; numbers must fit a float64; NUL characters are rejected because jsonb cannot store them. jsonb normalizes the stored payload (key order, whitespace, duplicate keys), so consumers compare JSON values rather than bytes. Payloads carry identifiers and minimal facts only, never contact data, tokens, passwords, or resume and document contents. + +Planned relay contract (TASK-009): the relay selects unpublished rows (`published_at IS NULL`) ordered by `position` on every pass and never keeps an `occurred_at` or `position` watermark, because a row with a smaller position can become visible after a larger one commits. It publishes the events of one aggregate in `aggregate_version` order and then sets `published_at`. Also planned: retry bookkeeping (attempt count and last error, added by an additive migration), retention of published rows, topics, and idempotent consumers. Bootstrap does not wire the transactor yet because no product usecase uses it; the first business transaction wires it together with a shared pool. ## Repository map and package purpose @@ -58,13 +83,14 @@ The MVP does not add a separate vector database, Kubernetes, or a search microse api/core/ public browser-to-Go contract and bundle api/ml/ internal Go-to-ML contract and bundle backend/cmd/app/main.go calls bootstrap.Run and reports errors +backend/cmd/migrate/ local migration status, up, and down-one backend/config/ shared runtime configuration backend/internal/domain/ product invariants, planned modules backend/internal/usecase/ application operations and orchestration backend/internal/port/ inbound and outbound interfaces backend/internal/adapter/ primary HTTP and secondary integrations backend/internal/bootstrap/ dependency wiring and process lifecycle -backend/db/ migrations and SQL queries +backend/db/ migrations, SQL queries, and the embedded migration set backend/codegen/ ogen server and ML-client configs, sqlc frontend/src/ app, pages, widgets, features, entities, shared frontend/codegen/ Orval configuration @@ -81,10 +107,10 @@ backend/ cmd/app/main.go calls bootstrap.Run and reports errors config/ shared runtime configuration internal/ - domain/ flat package; currently only .gitkeep + domain/ flat package; DomainEvent for the outbox usecase/health/ operational readiness usecase port/inbound/ readiness input boundary - port/outbound/ readiness, cache, and object storage boundaries + port/outbound/ readiness, cache, object storage, transaction, and outbox boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -93,21 +119,22 @@ backend/ router.go chi composition adapter/secondary/ ml/api/ generated client from backend/codegen/ogen-ml.yml + postgres/ pool, migrator, transactor, outbox writer, 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/ migrations and SQL queries; no product schema yet + db/ embedded migrations and SQL queries; outbox table, no product schema yet 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. Until the types are defined, the directory contains only `.gitkeep`. +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. Product domain types and usecase modules, mail/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, a PostgreSQL health query, a Redis cache adapter, and a SeaweedFS S3 adapter. Accounts, resumes, assessments, invitations, worker jobs, file workflows, mail, 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, a Redis cache adapter, and a SeaweedFS S3 adapter. Accounts, resumes, assessments, invitations, worker jobs, file workflows, mail, 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/`. @@ -210,7 +237,7 @@ The target screen stack is React Router, TanStack Query, React Hook Form, and Zo ## Future extensions -Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node; the outbox, relay, topics, and consumers are planned and not implemented. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI. +Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table and its transactional writer are implemented (see "Transactional outbox" above); the relay, topics, and consumers are planned and not implemented. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI. k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 3c78fc1..362a094 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -11,6 +11,8 @@ 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). + The backend build context is `backend/`, so Docker applies `backend/.dockerignore`. Local tools, caches, environment files, and build outputs are excluded from that context. The current `postgres:alpine` volume mounts at `/var/lib/postgresql`; the image stores data in a subdirectory for its major version. When the tag advances to a new major version, migrate an existing database with `pg_upgrade` or backup/restore. Updating the image alone does not convert the data. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index e99dabc..e2224c4 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -40,7 +40,7 @@ The repository contains a verifiable technical scaffold, not a product. Values b | wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` and `tool`) | | mockery | v3.8.0 | backend/go.mod (`tool`) | | golangci-lint | v2.14.0 | backend/go.mod (`tool`) | -| goose | v3.28.0 | backend/go.mod (`tool`) | +| goose | v3.28.0 | backend/go.mod (`require` and `tool`) | | chi | v5.3.2 | backend/go.mod | | pgx | v5.11.0 | backend/go.mod | | testcontainers-go | v0.44.0, including modules/postgres | backend/go.mod | @@ -48,14 +48,14 @@ 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, and a 404 for an unknown API route; it does not start ML. -- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, Redis through go-cachekit, and SeaweedFS through the S3 API. 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, and a transactor with the transactional outbox writer; Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap. - 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 a home page, 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`). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the backend has no Go Kafka client, topics, or readiness check for Kafka. - 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, mail delivery, the Go Kafka client, the transactional outbox and its relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ has no business schema, product usecase and adapter directories 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, mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains only the outbox table and no business schema, product usecase and adapter directories 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 @@ -141,6 +141,24 @@ ML runs as a separate FastAPI process. It currently provides operational health/ Write all source comments and docstrings in English. Keep canonical agent instructions in one English version; maintain user documentation in Russian and English. +### Database migrations + +Migrations are goose SQL files in `backend/db/migrations/` named `NNNNN_description.sql` with sequential five-digit versions. Each file has a `-- +goose Up` section and a working `-- +goose Down` section. sqlc reads the same directory as its schema, and `make -C backend lint-sql` lints it. `backend/db/migrations.go` embeds the files, so the binary applies exactly the schema it was built with. `make -C backend check` loads the embedded set without a database and fails on a malformed name, a missing Down section, or a duplicate version. A deployed migration is immutable; change the schema with a new file. Two branches that add the same version must renumber before merging. To create a file with the next sequential number, run `go tool goose -dir db/migrations -s create sql` in `backend/`. + +goose runs each migration in its own transaction. A statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`, needs a file of its own with the `-- +goose NO TRANSACTION` annotation. Every migration connection sets `lock_timeout` to 10 seconds, so DDL fails instead of queueing behind long transactions and blocking later queries on the table, and `statement_timeout` to 4 minutes. + +At startup bootstrap applies pending migrations after configuration validation and before the HTTP and metrics listeners open. The runner in `backend/internal/adapter/secondary/postgres/migrator.go` uses the goose v3 Provider API with the pgx database/sql driver and a PostgreSQL session advisory lock, so instances that start together apply migrations one at a time. Lock waiting and migration work are limited to five minutes. A migration error stops startup; the error omits the connection string and the password. Without `DATABASE_URL` the step is skipped with a warning, and readiness stays `not_ready` as before. + +`DATABASE_MIGRATE_ON_START` accepts only `true` or `false` (case-insensitive, surrounding spaces ignored); the default is `true`. It is a local and development option, for example to start the service against a database that a developer migrates by hand. The Compose stack does not pass it, and the backend image contains no separate migration command, so a deployed backend always migrates at startup and its database role needs DDL rights on the application schema. A separate migration role and job with a least-privilege runtime role is future work. + +For a local database, export `DATABASE_URL` in your shell and use these targets: + +- `make -C backend migrate-status` lists each embedded migration as applied, with its time, or pending. +- `make -C backend migrate-up` applies pending migrations. +- `make -C backend migrate-down-one` rolls back the latest applied migration. + +The targets run `backend/cmd/migrate` with the same runner, lock, and timeouts as startup. The Makefile contains no connection strings; keep credentials out of committed files. Integration tests apply all migrations to the PostgreSQL container from the shared bootstrap; see [TESTING.md](TESTING.md). + ## 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/en/TESTING.md b/docs/en/TESTING.md index 5af0cca..43f1173 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -36,7 +36,7 @@ Security checks run separately: `make -C security check` scans source/dependenci ## Current scaffold coverage -Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no accounts, assessments, search results, invitations, file workflows, or real model inference to validate as product behavior. +Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no accounts, assessments, search results, invitations, file workflows, or real model inference to validate as product behavior. API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub. @@ -48,7 +48,7 @@ The shared helper lives in `backend/integration_test/bootstrap_test.go`. Calling Call bootstrap once in the parent test and share its environment with its subtests. Each call creates separate containers with dynamic ports and a separate SeaweedFS volume when needed. Cleanup is registered through `t.Cleanup`, including partial startup. Redis outage and SeaweedFS recreation scenarios manage resources through environment helpers without affecting other tests. Tests fail when Docker is unavailable. -Bootstrap starts infrastructure and clients. The application HTTP server, business-schema migrations, ML, and product fixtures are not included yet. The full-environment test exercises combined PostgreSQL, Redis, and SeaweedFS readiness. +Bootstrap starts infrastructure and clients. When PostgreSQL is selected, it applies every embedded migration with the startup runner. `postgres_helpers_test.go` adds `env.newPool` for a pool to that database, `env.createIsolatedDatabase` for a separate database in the same container when a test changes the whole schema (for example up, down, and up again), `env.newPoolWithMaxConns` for concurrency tests that need one connection per transaction, and `truncateTables` for resetting shared tables between sequential subtests. Tests reach the transaction behind a unit of work only through `postgres.TransactionForIntegrationTest`, which is compiled only with the `integration` build tag. Test-only aggregates live in their own schema created by the test, not in production migrations. The application HTTP server, ML, and product fixtures are not included yet. The full-environment test exercises combined PostgreSQL, Redis, and SeaweedFS readiness. ## Integration test sharding diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 064921b..6f2de92 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -44,13 +44,38 @@ Go владеет авторизацией, подтвержденными ка Общие настройки Go принадлежат backend/config/ вне internal. Сейчас logkit 0.6.0, httpkit 0.7.0 и cachekit 0.7.0 из wahrwelt-kit используются для технических функций. Метрики реализованы ограниченным собственным collector/middleware, а pgxpool state не должен блокировать startup. pgkit и httpkit/metrics пока не используются; технические библиотеки не владеют бизнес-логикой. Не добавлять невыбранные JWT или WebSocket зависимости ради предполагаемых будущих сценариев. -PostgreSQL с pgx, sqlc и goose остается основной базой. SQL написан вручную, sqlc генерирует типизированный адаптер. goose управляет версионными миграциями. wire в bootstrap - compile-time сборка зависимостей; во время выполнения DI-контейнера нет. Worker и API используют один пул БД в целевом однопроцессном варианте. +PostgreSQL с pgx, sqlc и goose остается основной базой. SQL написан вручную, sqlc генерирует типизированный адаптер. goose управляет версионными миграциями: SQL-файлы встроены в бинарник, и backend применяет их при старте под advisory lock PostgreSQL до открытия своих listeners. wire в bootstrap - compile-time сборка зависимостей; во время выполнения DI-контейнера нет. Worker и API используют один пул БД в целевом однопроцессном варианте. Redis входит в основной Compose и подключен через `backend/internal/adapter/secondary/redis/` к outbound-порту кеша. Адаптер предоставляет Get/Set/Del с TTL, а bootstrap управляет подключением и закрытием клиента. Внутренний /readyz требует доступности PostgreSQL, Redis и bucket SeaweedFS. Кеш не является источником истины: вытеснение ключей и перезапуск Redis должны быть допустимы для будущих потребителей. Кеширование профилей, поиска, резюме и другие продуктовые правила еще не реализованы. SeaweedFS работает отдельным сервером в основном Compose. `backend/internal/adapter/secondary/seaweedfs/` реализует outbound-порт `ObjectStorage` через AWS SDK for Go v2: потоковые Put/Get и удаление объекта. SDK и S3-типы не выходят за границу адаптера. Bootstrap создает клиент, readiness проверяет bucket через HeadBucket. Хранилище закрыто внутри Docker-сети; Nginx не раздает его файлы напрямую. Загрузка резюме, проверка прав, ограничения содержимого и выдача PDF остаются будущими продуктовыми сценариями. Одноузловой Compose сохраняет данные и метаданные в volume, но не обеспечивает HA или внешнее резервное копирование. -Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, а Go клиент, outbox и relay пока не реализованы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу. +Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, таблица `outbox_events` и ее транзакционная запись уже есть, а Go клиент Kafka и relay пока не реализованы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу. + +### Transactional outbox + +Реализовано: миграция `backend/db/migrations/00001_create_outbox_events.sql` создает `outbox_events`. Колонки: + +- `position`: bigint identity, уникальный и монотонный в порядке вставки; relay читает по нему. +- `event_id`: uuid primary key, UUIDv7 создается в Go. +- `event_type`: имя в нижнем регистре через точку, не длиннее 128 байт. +- `schema_version`: integer больше нуля. +- `aggregate_type`: snake_case, не длиннее 64 байт. +- `aggregate_id`: uuid. +- `aggregate_version`: bigint больше нуля. +- `payload`: jsonb-объект. +- `occurred_at`: `clock_timestamp()` в момент вставки. Только для информации, порядок он не задает. +- `published_at`: null, пока relay не опубликует строку. + +Уникальный ключ по типу агрегата, ID агрегата, версии агрегата и типу события отклоняет второе событие того же типа для той же версии агрегата. Частичный индекс по `position` при `published_at IS NULL` обслуживает выборку relay. CHECK-ограничения повторяют доменные правила для версий, имен и payload-объекта как последнюю защиту. Ограничение размера payload есть только в Go: текстовый и бинарный размер jsonb отличаются от компактного входа, и проверка длины в БД могла бы отклонить событие, принятое доменом. + +Usecase пишет через outbound-порты. `Transactor.WithinTransaction(ctx, fn)` открывает одну транзакцию READ COMMITTED и передает `UnitOfWork`; все репозитории из него, включая `Outbox().Append(ctx, events...)`, работают в этой транзакции. Транзакция фиксируется, если fn вернула nil, и откатывается, если fn вернула ошибку, вызвала panic или ее контекст отменен. Повторный вызов `WithinTransaction` с контекстом callback возвращает `outbound.ErrNestedTransaction` и не открывает второе соединение. Конфликт по ID события или уникальному ключу возвращает ошибку, которая оборачивает `outbound.ErrOutboxEventConflict` и называет ограничение. Сетевая ошибка во время commit оставляет результат неизвестным, поэтому вызывающий код с повторами должен быть идемпотентным. + +Правило уникальности outbox - последняя защита, а не управление конкурентностью. Обновления агрегата по-прежнему проверяют ожидаемую версию (`UPDATE ... WHERE version = $n`), чтобы устаревший writer упал до записи события. + +`domain.NewDomainEvent` проверяет событие. Компактный JSON payload ограничен 16 KiB и 32 уровнями вложенности; числа должны помещаться в float64; символы NUL отклоняются, потому что jsonb не может их хранить. jsonb нормализует сохраненный payload (порядок ключей, пробелы, дублирующиеся ключи), поэтому потребители сравнивают JSON-значения, а не байты. Payload содержит только идентификаторы и минимальные факты, но не контакты, токены, пароли, содержимое резюме и документов. + +Запланированный контракт relay (TASK-009): на каждом проходе relay выбирает неопубликованные строки (`published_at IS NULL`) в порядке `position` и никогда не хранит watermark по `occurred_at` или `position`, потому что строка с меньшей позицией может стать видимой после фиксации строки с большей. События одного агрегата он публикует в порядке `aggregate_version` и затем заполняет `published_at`. Также запланированы учет повторов (счетчик попыток и последняя ошибка, добавятся аддитивной миграцией), хранение опубликованных строк, топики и идемпотентные потребители. Bootstrap пока не подключает transactor, потому что его не использует ни один продуктовый usecase; первая бизнес-транзакция подключит его вместе с общим пулом. ## Структура репозитория и назначение пакетов @@ -58,13 +83,14 @@ SeaweedFS работает отдельным сервером в основно api/core/ публичный контракт браузер-Go и bundle api/ml/ внутренний контракт Go-ML и bundle backend/cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку +backend/cmd/migrate/ локальные status, up и down-one для миграций backend/config/ общая конфигурация runtime backend/internal/domain/ продуктовые правила, планируемые модули backend/internal/usecase/ операции приложения и orchestration backend/internal/port/ inbound и outbound интерфейсы backend/internal/adapter/ primary HTTP и secondary интеграции backend/internal/bootstrap/ wiring зависимостей и lifecycle процесса -backend/db/ миграции и SQL-запросы +backend/db/ миграции, SQL-запросы и встроенный набор миграций backend/codegen/ конфигурация ogen для сервера и ML-клиента, sqlc frontend/src/ app, pages, widgets, features, entities, shared frontend/codegen/ конфигурация Orval @@ -81,10 +107,10 @@ backend/ cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку config/ общая конфигурация runtime internal/ - domain/ плоский пакет; пока только .gitkeep + domain/ плоский пакет; DomainEvent для outbox usecase/health/ operational readiness usecase port/inbound/ inbound граница readiness - port/outbound/ границы readiness, кеша и объектного хранилища + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции и outbox adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -93,21 +119,22 @@ backend/ router.go сборка chi router adapter/secondary/ ml/api/ generated client из backend/codegen/ogen-ml.yml + postgres/ pool, migrator, transactor, запись outbox, health check postgres/sqlc/ generated SQL adapter redis/ адаптер кеша и проверка Redis seaweedfs/ S3-адаптер и проверка bucket prometheus/ ограниченные Go/process и request metrics bootstrap/ конфигурация, wiring, lifecycle, shutdown - db/ миграции и SQL-запросы; продуктовой схемы пока нет + db/ встроенные миграции и SQL-запросы; таблица outbox, продуктовой схемы пока нет codegen/ конфигурация ogen и sqlc pkg/ резерв для обоснованных общих технических helpers ``` -Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Пока типы не определены, каталог содержит только `.gitkeep`. +Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. `domain/`, продуктовые `usecase/`, адаптеры почты и 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, Redis cache adapter и S3-адаптер SeaweedFS. Аккаунты, резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, Redis cache adapter и S3-адаптер SeaweedFS. Аккаунты, резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. @@ -210,7 +237,7 @@ contact_grant относится к паре кандидат-компания ## Будущее расширение -Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka; outbox, relay, топики и потребители запланированы и не реализованы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера. +Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka. Таблица outbox и ее транзакционная запись реализованы (см. "Transactional outbox" выше); relay, топики и потребители запланированы и не реализованы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера. k3s не входит в критический путь. Его можно рассмотреть при готовом обслуживаемом кластере или измеренной потребности в нескольких узлах. Один узел k3s не дает HA. Переход требует probes/resources, секретов, storage backup, ingress и проверенных NetworkPolicy. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 0228654..a4b7709 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -13,6 +13,8 @@ Основной файл 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#миграции-базы-данных). + Контекст сборки backend - каталог `backend/`, поэтому Docker применяет `backend/.dockerignore`. Локальные инструменты, кеши, файлы окружения и результаты сборки не отправляются в этот build context. Для текущего `postgres:alpine` volume монтируется в `/var/lib/postgresql`; образ размещает данные в подкаталоге своей major-версии. При переходе тега на новую major-версию существующую базу нужно мигрировать через `pg_upgrade` или backup/restore. Обновление образа само по себе не преобразует данные. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 687abcf..f5dcccf 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -40,7 +40,7 @@ Frontend зависимости выбираются из актуальных s | wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` и `tool`) | | mockery | v3.8.0 | backend/go.mod (`tool`) | | golangci-lint | v2.14.0 | backend/go.mod (`tool`) | -| goose | v3.28.0 | backend/go.mod (`tool`) | +| goose | v3.28.0 | backend/go.mod (`require` и `tool`) | | chi | v5.3.2 | backend/go.mod | | pgx | v5.11.0 | backend/go.mod | | testcontainers-go | v0.44.0, включая modules/postgres | backend/go.mod | @@ -48,14 +48,14 @@ 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 маршрута; ML он не запускает. -- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. +- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, и transactor с записью transactional outbox; Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. - 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`). - Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в backend нет Go клиента Kafka, топиков и проверки Kafka в readiness. - 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), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, transactional outbox и его relay, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть только таблица outbox и нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы @@ -141,6 +141,24 @@ ML - отдельный FastAPI процесс. Сейчас он предост Все комментарии и docstrings в коде пишутся на английском. Инструкции для агентов в корне и .agents также ведутся в единой английской версии; документация команды поддерживается на русском и английском. +### Миграции базы данных + +Миграции - SQL-файлы goose в `backend/db/migrations/` с именами `NNNNN_description.sql` и последовательными пятизначными версиями. В каждом файле есть секция `-- +goose Up` и работающая секция `-- +goose Down`. sqlc читает этот же каталог как схему, а `make -C backend lint-sql` проверяет его линтером. `backend/db/migrations.go` встраивает файлы в бинарник, поэтому он применяет ровно ту схему, с которой собран. `make -C backend check` загружает встроенный набор без базы данных и падает на неверном имени, отсутствующей секции Down или дублирующейся версии. Примененная на стенде миграция неизменна; схема меняется новым файлом. Две ветки с одинаковой версией должны перенумеровать файл перед слиянием. Чтобы создать файл со следующим номером, выполните `go tool goose -dir db/migrations -s create sql` в `backend/`. + +goose выполняет каждую миграцию в отдельной транзакции. Команде, которая не работает внутри транзакции, например `CREATE INDEX CONCURRENTLY`, нужен отдельный файл с аннотацией `-- +goose NO TRANSACTION`. Каждое соединение миграций устанавливает `lock_timeout` в 10 секунд, чтобы DDL падал, а не ждал за длинными транзакциями и не блокировал последующие запросы к таблице, и `statement_timeout` в 4 минуты. + +При старте bootstrap применяет ожидающие миграции после проверки конфигурации и до открытия HTTP и metrics listeners. Runner в `backend/internal/adapter/secondary/postgres/migrator.go` использует Provider API goose v3 с драйвером pgx для database/sql и сессионный advisory lock PostgreSQL, поэтому одновременно стартующие экземпляры применяют миграции по очереди. Ожидание блокировки и сами миграции ограничены пятью минутами. Ошибка миграции останавливает запуск; текст ошибки не содержит строку подключения и пароль. Без `DATABASE_URL` шаг пропускается с предупреждением, а readiness, как и раньше, остается `not_ready`. + +`DATABASE_MIGRATE_ON_START` принимает только `true` или `false` (без учета регистра, пробелы по краям игнорируются); по умолчанию `true`. Это опция для локальной разработки, например чтобы запустить сервис с базой, которую разработчик мигрирует вручную. Compose ее не передает, а в образе backend нет отдельной команды миграций, поэтому развернутый backend всегда мигрирует при старте, и его роли БД нужны права DDL на схему приложения. Отдельная роль и job миграций с минимальными правами runtime-роли - будущая работа. + +Для локальной базы экспортируйте `DATABASE_URL` в shell и используйте цели: + +- `make -C backend migrate-status` показывает каждую встроенную миграцию как примененную, со временем, или ожидающую. +- `make -C backend migrate-up` применяет ожидающие миграции. +- `make -C backend migrate-down-one` откатывает последнюю примененную миграцию. + +Цели запускают `backend/cmd/migrate` с тем же runner, блокировкой и таймаутами, что и старт сервиса. Makefile не содержит строк подключения; не храните учетные данные в коммитах. Интеграционные тесты применяют все миграции к контейнеру PostgreSQL из общего bootstrap; см. [TESTING.md](TESTING.md). + ## Читаемость Go-кода - Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 6915475..23c0213 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -36,7 +36,7 @@ make -C ml check-generated использует datamodel-code-generator --check ## Что покрывает текущий каркас -Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет пользователей, тестовых заданий, поисковой выдачи, приглашений, файлового workflow или реального model inference, которые можно было бы проверить как бизнес-результат. +Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет пользователей, тестовых заданий, поисковой выдачи, приглашений, файлового workflow или реального model inference, которые можно было бы проверить как бизнес-результат. API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub. @@ -48,7 +48,7 @@ Deployment smoke проверяет инфраструктурные маршр Вызывайте bootstrap один раз в родительском тесте и используйте окружение в его подтестах. Каждый вызов создает отдельные контейнеры с динамическими портами; для SeaweedFS также создается отдельный volume. Очистка зарегистрирована через `t.Cleanup`, включая частично запущенное окружение. Сценарии остановки Redis и пересоздания SeaweedFS управляют ресурсами через helpers этого окружения и не затрагивают другие тесты. При отсутствии Docker тесты завершаются ошибкой. -Bootstrap поднимает инфраструктуру и клиенты. HTTP-сервер приложения, миграции бизнес-схемы, ML и продуктовые фикстуры пока не входят в него. Проверка полного окружения использует общий readiness PostgreSQL, Redis и SeaweedFS. +Bootstrap поднимает инфраструктуру и клиенты. Если выбран PostgreSQL, он применяет все встроенные миграции тем же runner, что и старт сервиса. `postgres_helpers_test.go` добавляет `env.newPool` для пула к этой базе, `env.createIsolatedDatabase` для отдельной базы в том же контейнере, когда тест меняет всю схему (например up, down и повторный up), `env.newPoolWithMaxConns` для тестов конкурентности, которым нужно одно соединение на транзакцию, и `truncateTables` для сброса общих таблиц между последовательными подтестами. Тесты получают транзакцию из unit of work только через `postgres.TransactionForIntegrationTest`, который компилируется только с build tag `integration`. Тестовые агрегаты живут в собственной схеме, которую создает тест, а не в продуктовых миграциях. HTTP-сервер приложения, ML и продуктовые фикстуры пока не входят в него. Проверка полного окружения использует общий readiness PostgreSQL, Redis и SeaweedFS. ## Шардирование интеграционных тестов From e7d0d92ef9e22a7af293ecdda55b116d1ee4c046 Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 00:15:22 +0300 Subject: [PATCH 007/143] feat(identity): store users, email tokens, and sessions --- .../00002_create_identity_tables.sql | 167 +++ backend/db/queries/identity.sql | 333 +++++ backend/integration_test/identity_test.go | 1214 +++++++++++++++++ .../integration_test/postgres_helpers_test.go | 19 + .../postgres_migrations_test.go | 47 +- .../secondary/postgres/database_error.go | 54 + .../adapter/secondary/postgres/identity.go | 566 ++++++++ .../secondary/postgres/identity_test.go | 159 +++ .../secondary/postgres/sqlc/identity.sql.go | 689 ++++++++++ .../adapter/secondary/postgres/sqlc/models.go | 37 + .../secondary/postgres/sqlc/querier.go | 48 + .../adapter/secondary/postgres/transactor.go | 3 +- backend/internal/domain/email_address.go | 157 +++ backend/internal/domain/email_address_test.go | 145 ++ backend/internal/domain/email_token.go | 90 ++ backend/internal/domain/email_token_test.go | 66 + backend/internal/domain/secret_token.go | 88 ++ backend/internal/domain/secret_token_test.go | 80 ++ backend/internal/domain/session.go | 67 + backend/internal/domain/session_test.go | 46 + backend/internal/domain/user.go | 255 ++++ backend/internal/domain/user_test.go | 211 +++ backend/internal/port/outbound/identity.go | 165 +++ backend/internal/port/outbound/transaction.go | 14 +- docs/en/ARCHITECTURE.md | 40 +- docs/en/DEVELOPMENT.md | 10 +- docs/en/TESTING.md | 2 +- docs/ru/ARCHITECTURE.md | 40 +- docs/ru/DEVELOPMENT.md | 10 +- docs/ru/TESTING.md | 2 +- 30 files changed, 4792 insertions(+), 32 deletions(-) create mode 100644 backend/db/migrations/00002_create_identity_tables.sql create mode 100644 backend/db/queries/identity.sql create mode 100644 backend/integration_test/identity_test.go create mode 100644 backend/internal/adapter/secondary/postgres/database_error.go create mode 100644 backend/internal/adapter/secondary/postgres/identity.go create mode 100644 backend/internal/adapter/secondary/postgres/identity_test.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go create mode 100644 backend/internal/domain/email_address.go create mode 100644 backend/internal/domain/email_address_test.go create mode 100644 backend/internal/domain/email_token.go create mode 100644 backend/internal/domain/email_token_test.go create mode 100644 backend/internal/domain/secret_token.go create mode 100644 backend/internal/domain/secret_token_test.go create mode 100644 backend/internal/domain/session.go create mode 100644 backend/internal/domain/session_test.go create mode 100644 backend/internal/domain/user.go create mode 100644 backend/internal/domain/user_test.go create mode 100644 backend/internal/port/outbound/identity.go diff --git a/backend/db/migrations/00002_create_identity_tables.sql b/backend/db/migrations/00002_create_identity_tables.sql new file mode 100644 index 0000000..7733be4 --- /dev/null +++ b/backend/db/migrations/00002_create_identity_tables.sql @@ -0,0 +1,167 @@ +-- +goose Up +-- Identity storage: accounts, one-time email tokens, and server-side sessions. +-- Passwords, raw email tokens, and raw session tokens are never stored; only +-- an Argon2id PHC string and SHA-256 digests are. Every timestamp comes from +-- the application clock, so expiry checks and the stored deadlines use one +-- clock. Enum-like columns are text with CHECK constraints rather than +-- PostgreSQL enum types: a new value then changes one constraint in a later +-- migration, which can also be rolled back, while an enum value cannot be +-- removed and cannot be used in the transaction that adds it. +CREATE TABLE users ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + -- Delivery form: trimmed ASCII, letter case as typed. + email text NOT NULL, + -- Comparison key computed in Go: the delivery form with A-Z lowercased. + email_normalized text NOT NULL, + -- Argon2id PHC string; never the password. + password_hash text NOT NULL, + scenario text NOT NULL, + onboarding_step text NOT NULL, + email_verified_at timestamptz, + -- Advanced on every registration of the unverified email. Email tokens + -- are bound to the version they were issued for. + registration_version bigint NOT NULL, + -- Time of the latest registration; the planned cleanup of unverified + -- accounts counts its deadline from here. + last_registered_at timestamptz NOT NULL, + -- Optimistic concurrency version, advanced on every update. + version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT users_pkey PRIMARY KEY (id), + CONSTRAINT users_email_normalized_key UNIQUE (email_normalized), + -- Addresses are ASCII until the mailer supports SMTPUTF8: one byte per + -- character in the UTF-8 database encoding. + CONSTRAINT users_email_ascii CHECK ( + char_length(email) BETWEEN 3 AND 254 + AND octet_length(email) = char_length(email) + ), + -- translate() maps A-Z by code point, independent of the collation, + -- unlike lower(). + CONSTRAINT users_email_normalized_rule CHECK ( + email_normalized = translate( + email, + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'abcdefghijklmnopqrstuvwxyz' + ) + ), + CONSTRAINT users_password_hash_format CHECK ( + char_length(password_hash) <= 512 + AND password_hash + ~ '^\$argon2id\$v=19\$m=[0-9]+,t=[0-9]+,p=[0-9]+\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$' + ), + CONSTRAINT users_scenario_onboarding_step CHECK ( + ( + scenario = 'candidate' + AND onboarding_step IN ( + 'candidate_consents', + 'candidate_profile', + 'candidate_questionnaire', + 'candidate_assessment', + 'completed' + ) + ) + OR ( + scenario = 'employer' + AND onboarding_step IN ('employer_company', 'completed') + ) + ), + CONSTRAINT users_registration_version_positive CHECK ( + registration_version > 0 + ), + CONSTRAINT users_version_positive CHECK (version > 0), + CONSTRAINT users_timestamps_after_creation CHECK ( + updated_at >= created_at + AND last_registered_at >= created_at + AND (email_verified_at IS NULL OR email_verified_at >= created_at) + ) +); + +-- Supports the planned cleanup of accounts that stay unverified after their +-- latest registration. Verified accounts are not indexed. +CREATE INDEX users_unverified_last_registered_at_idx +ON users (last_registered_at) +WHERE email_verified_at IS NULL; + +CREATE TABLE email_tokens ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + user_id uuid NOT NULL, + purpose text NOT NULL, + -- SHA-256 of the raw token as 32 raw bytes: half the size of hex text, + -- with an exact length check and no letter-case or encoding variants. + token_hash bytea NOT NULL, + registration_version bigint NOT NULL, + created_at timestamptz NOT NULL, + expires_at timestamptz NOT NULL, + consumed_at timestamptz, + -- Set when a re-registration or a resend replaces the token. + invalidated_at timestamptz, + CONSTRAINT email_tokens_pkey PRIMARY KEY (id), + CONSTRAINT email_tokens_token_hash_key UNIQUE (token_hash), + CONSTRAINT email_tokens_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT email_tokens_purpose_known CHECK ( + purpose IN ('email_verification') + ), + CONSTRAINT email_tokens_token_hash_sha256 CHECK ( + octet_length(token_hash) = 32 + ), + CONSTRAINT email_tokens_registration_version_positive CHECK ( + registration_version > 0 + ), + CONSTRAINT email_tokens_expiry_after_creation CHECK ( + expires_at > created_at + ), + -- A token ends at most once: either consumed or invalidated. + CONSTRAINT email_tokens_single_outcome CHECK ( + consumed_at IS NULL OR invalidated_at IS NULL + ), + CONSTRAINT email_tokens_outcome_after_creation CHECK ( + (consumed_at IS NULL OR consumed_at >= created_at) + AND (invalidated_at IS NULL OR invalidated_at >= created_at) + ) +); + +-- Serves invalidation of a user's tokens for one purpose and the cascade +-- delete of a user's tokens. +CREATE INDEX email_tokens_user_id_purpose_idx +ON email_tokens (user_id, purpose); + +CREATE TABLE sessions ( + -- UUIDv7 generated in Go; internal only, never sent to the client. + id uuid NOT NULL, + user_id uuid NOT NULL, + -- SHA-256 of the raw session token that the cookie carries. + token_hash bytea NOT NULL, + created_at timestamptz NOT NULL, + -- The idle timeout counts from here. + last_seen_at timestamptz NOT NULL, + -- Absolute deadline fixed at creation. + expires_at timestamptz NOT NULL, + revoked_at timestamptz, + CONSTRAINT sessions_pkey PRIMARY KEY (id), + CONSTRAINT sessions_token_hash_key UNIQUE (token_hash), + CONSTRAINT sessions_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT sessions_token_hash_sha256 CHECK ( + octet_length(token_hash) = 32 + ), + CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at), + CONSTRAINT sessions_last_seen_after_creation CHECK ( + last_seen_at >= created_at + ), + CONSTRAINT sessions_revoked_after_creation CHECK ( + revoked_at IS NULL OR revoked_at >= created_at + ) +); + +-- Serves revocation of all of a user's sessions and the cascade delete. +CREATE INDEX sessions_user_id_idx +ON sessions (user_id); + +-- +goose Down +DROP TABLE sessions; +DROP TABLE email_tokens; +DROP TABLE users; diff --git a/backend/db/queries/identity.sql b/backend/db/queries/identity.sql new file mode 100644 index 0000000..d3e86ce --- /dev/null +++ b/backend/db/queries/identity.sql @@ -0,0 +1,333 @@ +-- name: InsertUser :exec +INSERT INTO users ( + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(email), + sqlc.arg(email_normalized), + sqlc.arg(password_hash), + sqlc.arg(scenario), + sqlc.arg(onboarding_step), + sqlc.narg(email_verified_at), + sqlc.arg(registration_version), + sqlc.arg(last_registered_at), + sqlc.arg(version), + sqlc.arg(created_at), + sqlc.arg(updated_at) +); + +-- name: GetUserByID :one +SELECT + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +FROM users +WHERE id = sqlc.arg(id); + +-- name: GetUserByEmailNormalized :one +SELECT + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +FROM users +WHERE email_normalized = sqlc.arg(email_normalized); + +-- Replaces the registration of an unverified account and advances the +-- registration version in the same statement, so no caller can choose it. +-- The version check rejects a writer that read an older row; a verified +-- account never changes. +-- name: UpdateUserRegistration :one +UPDATE users +SET + email = sqlc.arg(email), + password_hash = sqlc.arg(password_hash), + scenario = sqlc.arg(scenario), + onboarding_step = sqlc.arg(onboarding_step), + registration_version = registration_version + 1, + last_registered_at = sqlc.arg(last_registered_at), + updated_at = sqlc.arg(updated_at), + version = version + 1 +WHERE + id = sqlc.arg(id) + AND version = sqlc.arg(expected_version) + AND email_verified_at IS NULL +RETURNING + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at; + +-- Verifies the email only for the registration version the consumed token +-- was issued for. +-- name: MarkUserEmailVerified :one +UPDATE users +SET + email_verified_at = sqlc.arg(verified_at), + updated_at = sqlc.arg(verified_at), + version = version + 1 +WHERE + id = sqlc.arg(id) + AND registration_version = sqlc.arg(registration_version) + AND email_verified_at IS NULL +RETURNING + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at; + +-- Deletes one batch of accounts that stayed unverified since before cutoff, +-- oldest first, with their tokens and sessions. Every lock is taken with SKIP +-- LOCKED, so the statement never waits: an account whose row is locked, for +-- example by a re-registration or a token insert, is skipped, and so is an +-- account with any token or session row locked, for example by a +-- confirmation that consumed a token. Skipped accounts stay for the next run. +-- Taking the account lock before the token locks is the reverse of the +-- documented order, which is safe only because no lock here waits. +-- name: DeleteUnverifiedUsersRegisteredBefore :execrows +WITH candidate AS ( + SELECT stale.id + FROM users AS stale + WHERE + stale.email_verified_at IS NULL + AND stale.last_registered_at < sqlc.arg(cutoff) + ORDER BY stale.last_registered_at + LIMIT sqlc.arg(batch_limit) + FOR UPDATE SKIP LOCKED +), + +locked_token AS ( + SELECT token.user_id + FROM email_tokens AS token + WHERE token.user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +locked_session AS ( + SELECT session.user_id + FROM sessions AS session + WHERE session.user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +-- An account qualifies only when every token and session row visible to the +-- statement was locked above. +deletable AS ( + SELECT candidate.id + FROM candidate + WHERE + ( + SELECT count(*) FROM email_tokens AS token + WHERE token.user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_token + WHERE locked_token.user_id = candidate.id + ) + AND ( + SELECT count(*) FROM sessions AS session + WHERE session.user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_session + WHERE locked_session.user_id = candidate.id + ) +) + +DELETE FROM users +USING deletable +WHERE users.id = deletable.id; + +-- name: InsertEmailToken :exec +INSERT INTO email_tokens ( + id, + user_id, + purpose, + token_hash, + registration_version, + created_at, + expires_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(user_id), + sqlc.arg(purpose), + sqlc.arg(token_hash), + sqlc.arg(registration_version), + sqlc.arg(created_at), + sqlc.arg(expires_at) +); + +-- name: InvalidateActiveEmailTokens :execrows +UPDATE email_tokens +SET invalidated_at = sqlc.arg(invalidated_at) +WHERE + user_id = sqlc.arg(user_id) + AND purpose = sqlc.arg(purpose) + AND consumed_at IS NULL + AND invalidated_at IS NULL; + +-- Consumes a token in one statement. Concurrent callers queue on the token +-- row lock; under READ COMMITTED each waiter re-checks the WHERE clause +-- against the committed row, so exactly one of them updates it. The join +-- compares the registration version with the account row as the statement +-- reads it, without locking that row, so it rejects a token from an earlier +-- registration that already committed but not one that commits afterwards. +-- The confirmation guarantee therefore needs MarkUserEmailVerified with the +-- returned registration version in the same transaction, rolled back when it +-- matches no row. +-- name: ConsumeEmailToken :one +UPDATE email_tokens AS token +SET consumed_at = sqlc.arg(consumed_at) +FROM users AS owner +WHERE + token.token_hash = sqlc.arg(token_hash) + AND token.purpose = sqlc.arg(purpose) + AND token.consumed_at IS NULL + AND token.invalidated_at IS NULL + AND token.expires_at > sqlc.arg(consumed_at) + AND owner.id = token.user_id + AND owner.registration_version = token.registration_version +RETURNING + token.id, + token.user_id, + token.purpose, + token.token_hash, + token.registration_version, + token.created_at, + token.expires_at, + token.consumed_at, + token.invalidated_at; + +-- Explains why ConsumeEmailToken matched no row. +-- name: GetEmailTokenState :one +SELECT + token.consumed_at, + token.invalidated_at, + token.expires_at, + owner.registration_version = token.registration_version AS current_registration +FROM email_tokens AS token +INNER JOIN users AS owner ON token.user_id = owner.id +WHERE + token.token_hash = sqlc.arg(token_hash) + AND token.purpose = sqlc.arg(purpose); + +-- name: InsertSession :exec +INSERT INTO sessions ( + id, + user_id, + token_hash, + created_at, + last_seen_at, + expires_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(user_id), + sqlc.arg(token_hash), + sqlc.arg(created_at), + sqlc.arg(last_seen_at), + sqlc.arg(expires_at) +); + +-- name: GetActiveSessionByTokenHash :one +SELECT + id, + user_id, + token_hash, + created_at, + last_seen_at, + expires_at, + revoked_at +FROM sessions +WHERE + token_hash = sqlc.arg(token_hash) + AND revoked_at IS NULL + AND expires_at > sqlc.arg(at) + AND last_seen_at > sqlc.arg(idle_cutoff); + +-- Records activity on an active session and reports whether it is active. +-- The row is written only when last_seen_at is older than touch_cutoff, so +-- frequent requests do not rewrite it. last_seen_at never moves back, and a +-- revoked, expired, or idle session is not revived; the update re-checks +-- those conditions against a concurrent change. +-- name: TouchSession :one +WITH active_session AS ( + SELECT candidate.id + FROM sessions AS candidate + WHERE + candidate.id = sqlc.arg(id) + AND candidate.revoked_at IS NULL + AND candidate.expires_at > sqlc.arg(at) + AND candidate.last_seen_at > sqlc.arg(idle_cutoff) +), + +touched AS ( + UPDATE sessions + SET last_seen_at = sqlc.arg(at) + WHERE + sessions.id = sqlc.arg(id) + AND sessions.revoked_at IS NULL + AND sessions.expires_at > sqlc.arg(at) + AND sessions.last_seen_at > sqlc.arg(idle_cutoff) + AND sessions.last_seen_at < sqlc.arg(touch_cutoff) + RETURNING sessions.id +) + +SELECT + exists(SELECT 1 FROM active_session) AS active, + exists(SELECT 1 FROM touched) AS touched; + +-- name: RevokeSession :execrows +UPDATE sessions +SET revoked_at = sqlc.arg(revoked_at) +WHERE + id = sqlc.arg(id) + AND revoked_at IS NULL; + +-- name: RevokeUserSessions :execrows +UPDATE sessions +SET revoked_at = sqlc.arg(revoked_at) +WHERE + user_id = sqlc.arg(user_id) + AND revoked_at IS NULL; diff --git a/backend/integration_test/identity_test.go b/backend/integration_test/identity_test.go new file mode 100644 index 0000000..b75e683 --- /dev/null +++ b/backend/integration_test/identity_test.go @@ -0,0 +1,1214 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "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" +) + +const ( + identityTestTimeout = 2 * time.Minute + parallelConsumers = 10 + tokenLifetime = 24 * time.Hour + sessionLifetime = 7 * 24 * time.Hour + sessionIdleTimeout = 24 * time.Hour + signedInSessions = 3 + staleAccounts = 3 + cleanupBatch = 2 + cleanupLockTimeout = 200 * time.Millisecond + // heldTransactionConns covers a held transaction, a contender, and a spare. + heldTransactionConns = 3 + // A syntactically valid Argon2id PHC string; the tests never hash a password. + identityTestPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA" +) + +var ( + usersTable = pgx.Identifier{"users"} + emailTokensTable = pgx.Identifier{"email_tokens"} + sessionsTable = pgx.Identifier{"sessions"} + identityTables = []pgx.Identifier{usersTable, emailTokensTable, sessionsTable} +) + +type identityFixture struct { + ctx context.Context + pool *pgxpool.Pool + store *postgresadapter.IdentityStore + // now is truncated to microseconds, the precision PostgreSQL stores. + now time.Time +} + +func TestIdentityRepositories(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), identityTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + transactor := postgresadapter.NewTransactor(pool) + fixture := identityFixture{ + ctx: ctx, + pool: pool, + store: postgresadapter.NewIdentityStore(pool), + now: time.Now().UTC().Truncate(time.Microsecond), + } + + // Subtests share tables and run sequentially; each starts from empty tables. + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, identityTables...) + } + + t.Run("stores an account and finds it by ID and by any case of its email", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "Alice.Smith@Example.com", domain.ScenarioCandidate, fixture.now) + lookup := mustEmail(t, " alice.smith@EXAMPLE.COM ") + byEmail, err := fixture.store.Users().GetByEmail(ctx, lookup) + if err != nil { + t.Fatalf("GetByEmail() error = %v", err) + } + assertSameUser(t, byEmail, user) + if byEmail.Email.Address() != "Alice.Smith@Example.com" { + t.Fatalf("stored delivery address = %q, want the registered form", byEmail.Email.Address()) + } + byID, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + assertSameUser(t, byID, user) + + if _, err := fixture.store.Users().GetByID(ctx, uuid.New()); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(unknown) error = %v, want ErrUserNotFound", err) + } + if _, err := fixture.store.Users().GetByEmail(ctx, mustEmail(t, "nobody@example.com")); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByEmail(unknown) error = %v, want ErrUserNotFound", err) + } + }) + + t.Run("letter-case variants of an email conflict", func(t *testing.T) { + reset(t) + fixture.createUser(t, "Jose@Example.com", domain.ScenarioCandidate, fixture.now) + for _, variant := range []string{"jose@example.com", "JOSE@EXAMPLE.COM"} { + duplicate := fixture.newUser(t, variant, domain.ScenarioEmployer, fixture.now) + err := fixture.store.Users().Create(ctx, duplicate) + if !errors.Is(err, outbound.ErrEmailTaken) { + t.Fatalf("Create(%q) error = %v, want ErrEmailTaken", variant, err) + } + if !strings.Contains(err.Error(), "users_email_normalized_key") { + t.Fatalf("Create(%q) error = %v, want the constraint name", variant, err) + } + } + assertRowCount(ctx, t, pool, usersTable, 1) + }) + + t.Run("stores only hashes of email and session tokens", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "hashes@example.com", domain.ScenarioCandidate, fixture.now) + rawEmailToken, emailToken := fixture.issueToken(t, user, fixture.now, tokenLifetime) + rawSessionToken, session := fixture.startSession(t, user, fixture.now) + + for _, check := range []struct { + table pgx.Identifier + id uuid.UUID + raw domain.SecretToken + }{ + {table: emailTokensTable, id: emailToken.ID, raw: rawEmailToken}, + {table: sessionsTable, id: session.ID, raw: rawSessionToken}, + } { + var rowText string + var storedHash []byte + err := pool.QueryRow(ctx, fmt.Sprintf(` + SELECT row_to_json(stored)::text, stored.token_hash + FROM %s AS stored WHERE stored.id = $1`, check.table.Sanitize()), check.id).Scan(&rowText, &storedHash) + if err != nil { + t.Fatalf("read %s row: %v", check.table.Sanitize(), err) + } + if strings.Contains(rowText, check.raw.Reveal()) { + t.Fatalf("%s row contains the raw token", check.table.Sanitize()) + } + if want := sha256.Sum256([]byte(check.raw.Reveal())); string(storedHash) != string(want[:]) { + t.Fatalf("%s token_hash is not the SHA-256 digest of the raw token", check.table.Sanitize()) + } + } + for _, raw := range []domain.SecretToken{rawEmailToken, rawSessionToken} { + var matches int + err := pool.QueryRow(ctx, ` + SELECT + (SELECT count(*) FROM users AS u WHERE strpos(row_to_json(u)::text, $1) > 0) + + (SELECT count(*) FROM email_tokens AS e WHERE strpos(row_to_json(e)::text, $1) > 0) + + (SELECT count(*) FROM sessions AS s WHERE strpos(row_to_json(s)::text, $1) > 0)`, + raw.Reveal()).Scan(&matches) + if err != nil { + t.Fatalf("search identity tables for a raw token: %v", err) + } + if matches != 0 { + t.Fatalf("%d identity rows contain a raw token", matches) + } + } + + // Every secret-bearing column in the identity schema is a hash. + rows, err := pool.Query(ctx, ` + SELECT table_name || '.' || column_name FROM information_schema.columns + WHERE table_schema = 'public' + AND table_name IN ('users', 'email_tokens', 'sessions') + AND (column_name LIKE '%password%' OR column_name LIKE '%token%' OR column_name LIKE '%secret%') + AND column_name NOT LIKE '%\_hash' + ORDER BY 1`) + if err != nil { + t.Fatalf("list secret-bearing columns: %v", err) + } + unhashed, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + t.Fatalf("read secret-bearing columns: %v", err) + } + if len(unhashed) != 0 { + t.Fatalf("identity columns store secrets without hashing: %v", unhashed) + } + }) + + t.Run("re-registration advances versions and rejects a stale writer or a verified account", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "rereg@example.com", domain.ScenarioCandidate, fixture.now) + later := fixture.now.Add(time.Hour) + changed, err := user.ReRegister(fixture.registration(t, "ReReg@Example.com", domain.ScenarioEmployer, later)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + stored, err := fixture.store.Users().UpdateRegistration(ctx, changed) + if err != nil { + t.Fatalf("UpdateRegistration() error = %v", err) + } + if stored.Version != 2 || stored.RegistrationVersion != 2 || stored.Scenario != domain.ScenarioEmployer || + stored.OnboardingStep != domain.OnboardingStepEmployerCompany || stored.Email.Address() != "ReReg@Example.com" || + !stored.LastRegisteredAt.Equal(later) || !stored.CreatedAt.Equal(fixture.now) { + t.Fatalf("UpdateRegistration() = %+v", stored) + } + + // A writer that still holds version 1 must not overwrite version 2. + stale, err := user.ReRegister(fixture.registration(t, "rereg@example.com", domain.ScenarioCandidate, later)) + if err != nil { + t.Fatalf("ReRegister(stale) error = %v", err) + } + if _, err := fixture.store.Users().UpdateRegistration(ctx, stale); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("UpdateRegistration(stale) error = %v, want ErrUserVersionConflict", err) + } + + verified, err := fixture.store.Users().MarkEmailVerified(ctx, user.ID, stored.RegistrationVersion, later) + if err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + // The stored row is verified even if a caller still holds the unverified view. + unverifiedView := verified + unverifiedView.EmailVerifiedAt = nil + afterVerification, err := unverifiedView.ReRegister(fixture.registration(t, "rereg@example.com", domain.ScenarioCandidate, later)) + if err != nil { + t.Fatalf("ReRegister(unverified view) error = %v", err) + } + if _, err := fixture.store.Users().UpdateRegistration(ctx, afterVerification); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("UpdateRegistration(verified account) error = %v, want ErrUserVersionConflict", err) + } + current, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + assertSameUser(t, current, verified) + }) + + t.Run("verification requires the current registration version and happens once", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "verify@example.com", domain.ScenarioCandidate, fixture.now) + users := fixture.store.Users() + if _, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion+1, fixture.now); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("MarkEmailVerified(other registration version) error = %v, want ErrUserVersionConflict", err) + } + verified, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, fixture.now) + if err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + if !verified.EmailVerified() || !verified.EmailVerifiedAt.Equal(fixture.now) || verified.Version != user.Version+1 { + t.Fatalf("MarkEmailVerified() = %+v", verified) + } + if _, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, fixture.now); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("second MarkEmailVerified() error = %v, want ErrUserVersionConflict", err) + } + }) + + t.Run("parallel confirmations consume a token exactly once", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "parallel@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + // One connection per confirmation plus a spare, so nothing queues in the pool. + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, parallelConsumers+1)) + at := fixture.now.Add(time.Minute) + + errs := make([]error, parallelConsumers) + start := make(chan struct{}) + var group sync.WaitGroup + for index := range parallelConsumers { + group.Go(func() { + <-start + errs[index] = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + token, err := unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, at) + if err != nil { + return err + } + _, err = unit.Users().MarkEmailVerified(ctx, token.UserID, token.RegistrationVersion, at) + return err + }) + }) + } + close(start) + group.Wait() + + successes := 0 + for index, err := range errs { + switch { + case err == nil: + successes++ + case errors.Is(err, outbound.ErrEmailTokenConsumed): + default: + t.Fatalf("confirmation %d error = %v, want nil or ErrEmailTokenConsumed", index, err) + } + } + if successes != 1 { + t.Fatalf("%d confirmations succeeded, want exactly 1", successes) + } + verified, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + if !verified.EmailVerified() || verified.Version != user.Version+1 { + t.Fatalf("account after confirmations = %+v, want verified once", verified) + } + }) + + t.Run("parallel consumes outside a transaction succeed exactly once", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "autocommit@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + concurrentStore := postgresadapter.NewIdentityStore(env.newPoolWithMaxConns(ctx, t, parallelConsumers+1)) + errs := make([]error, parallelConsumers) + start := make(chan struct{}) + var group sync.WaitGroup + for index := range parallelConsumers { + group.Go(func() { + <-start + _, errs[index] = concurrentStore.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, fixture.now) + }) + } + close(start) + group.Wait() + successes := 0 + for index, err := range errs { + switch { + case err == nil: + successes++ + case errors.Is(err, outbound.ErrEmailTokenConsumed): + default: + t.Fatalf("consume %d error = %v, want nil or ErrEmailTokenConsumed", index, err) + } + } + if successes != 1 { + t.Fatalf("%d consumes succeeded, want exactly 1", successes) + } + }) + + t.Run("expired, invalidated, superseded, unknown, and wrong-purpose tokens are not consumable", func(t *testing.T) { + reset(t) + tokens := fixture.store.EmailTokens() + purpose := domain.EmailTokenPurposeEmailVerification + user := fixture.createUser(t, "states@example.com", domain.ScenarioCandidate, fixture.now) + other := fixture.createUser(t, "other@example.com", domain.ScenarioEmployer, fixture.now) + + expired, _ := fixture.issueToken(t, user, fixture.now.Add(-2*time.Hour), time.Hour) + assertConsumeError(ctx, t, tokens, expired, fixture.now, outbound.ErrEmailTokenExpired) + // The deadline itself is already past. + atDeadline, deadlineToken := fixture.issueToken(t, user, fixture.now, time.Hour) + assertConsumeError(ctx, t, tokens, atDeadline, deadlineToken.ExpiresAt, outbound.ErrEmailTokenExpired) + + unknown, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + assertConsumeError(ctx, t, tokens, unknown, fixture.now, outbound.ErrEmailTokenNotFound) + if _, err := tokens.Consume(ctx, atDeadline.Hash(), "password_reset", fixture.now); !errors.Is(err, outbound.ErrEmailTokenNotFound) { + t.Fatalf("Consume(wrong purpose) error = %v, want ErrEmailTokenNotFound", err) + } + + consumed, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + if _, err := tokens.Consume(ctx, consumed.Hash(), purpose, fixture.now); err != nil { + t.Fatalf("Consume() error = %v", err) + } + // A consumed token stays consumed after its deadline. + assertConsumeError(ctx, t, tokens, consumed, fixture.now.Add(2*tokenLifetime), outbound.ErrEmailTokenConsumed) + + first, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + second, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + otherToken, _ := fixture.issueToken(t, other, fixture.now, tokenLifetime) + // The two active tokens and the expired, unmarked ones are invalidated; + // the consumed token and the other user's token are not. + invalidated, err := tokens.InvalidateActive(ctx, user.ID, purpose, fixture.now) + if err != nil { + t.Fatalf("InvalidateActive() error = %v", err) + } + if invalidated != 4 { + t.Fatalf("InvalidateActive() = %d, want 4", invalidated) + } + assertConsumeError(ctx, t, tokens, first, fixture.now, outbound.ErrEmailTokenInvalidated) + assertConsumeError(ctx, t, tokens, second, fixture.now, outbound.ErrEmailTokenInvalidated) + assertConsumeError(ctx, t, tokens, consumed, fixture.now, outbound.ErrEmailTokenConsumed) + if again, err := tokens.InvalidateActive(ctx, user.ID, purpose, fixture.now); err != nil || again != 0 { + t.Fatalf("second InvalidateActive() = %d, %v, want 0", again, err) + } + // A token issued after the invalidation works. + fresh, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + if _, err := tokens.Consume(ctx, fresh.Hash(), purpose, fixture.now); err != nil { + t.Fatalf("Consume(fresh) error = %v", err) + } + if _, err := tokens.Consume(ctx, otherToken.Hash(), purpose, fixture.now); err != nil { + t.Fatalf("Consume(other user's token) error = %v", err) + } + + // A token bound to an earlier registration version never confirms the + // newer registration, even when nobody invalidated it. + superseded, _ := fixture.issueToken(t, other, fixture.now, tokenLifetime) + reRegistered, err := other.ReRegister(fixture.registration(t, "other@example.com", domain.ScenarioCandidate, fixture.now)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + if _, err := fixture.store.Users().UpdateRegistration(ctx, reRegistered); err != nil { + t.Fatalf("UpdateRegistration() error = %v", err) + } + assertConsumeError(ctx, t, tokens, superseded, fixture.now, outbound.ErrEmailTokenInvalidated) + }) + + t.Run("tokens and sessions for a missing account report ErrUserNotFound", func(t *testing.T) { + reset(t) + missing := uuid.New() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ + UserID: missing, Purpose: domain.EmailTokenPurposeEmailVerification, TokenHash: raw.Hash(), + RegistrationVersion: 1, IssuedAt: fixture.now, Lifetime: tokenLifetime, + }) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + if err := fixture.store.EmailTokens().Insert(ctx, token); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("Insert(missing user) error = %v, want ErrUserNotFound", err) + } + session, err := domain.NewSession(domain.NewSessionInput{ + UserID: missing, TokenHash: raw.Hash(), StartedAt: fixture.now, AbsoluteLifetime: sessionLifetime, + }) + if err != nil { + t.Fatalf("NewSession() error = %v", err) + } + if err := fixture.store.Sessions().Create(ctx, session); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("Create(missing user) error = %v, want ErrUserNotFound", err) + } + }) + + t.Run("duplicate token hashes are rejected", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "duplicate@example.com", domain.ScenarioCandidate, fixture.now) + _, first := fixture.issueToken(t, user, fixture.now, tokenLifetime) + second := first + second.ID = uuid.New() + if err := fixture.store.EmailTokens().Insert(ctx, second); !errors.Is(err, outbound.ErrTokenHashConflict) { + t.Fatalf("Insert(duplicate hash) error = %v, want ErrTokenHashConflict", err) + } + _, session := fixture.startSession(t, user, fixture.now) + duplicateSession := session + duplicateSession.ID = uuid.New() + if err := fixture.store.Sessions().Create(ctx, duplicateSession); !errors.Is(err, outbound.ErrTokenHashConflict) { + t.Fatalf("Create(duplicate session hash) error = %v, want ErrTokenHashConflict", err) + } + }) + + t.Run("sessions are found while active and stop at idle, absolute, and revocation limits", func(t *testing.T) { + reset(t) + sessions := fixture.store.Sessions() + user := fixture.createUser(t, "session@example.com", domain.ScenarioCandidate, fixture.now) + raw, session := fixture.startSession(t, user, fixture.now) + + found, err := sessions.FindActive(ctx, raw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout) + if err != nil { + t.Fatalf("FindActive() error = %v", err) + } + assertSameSession(t, found, session) + + touchedAt := fixture.now.Add(23 * time.Hour) + if err := sessions.Touch(ctx, session.ID, touchedAt, sessionIdleTimeout); err != nil { + t.Fatalf("Touch() error = %v", err) + } + // An older activity time does not move last_seen_at back. + if err := sessions.Touch(ctx, session.ID, fixture.now.Add(time.Hour), sessionIdleTimeout); err != nil { + t.Fatalf("Touch(older) error = %v", err) + } + found, err = sessions.FindActive(ctx, raw.Hash(), touchedAt.Add(sessionIdleTimeout-time.Second), sessionIdleTimeout) + if err != nil { + t.Fatalf("FindActive(before idle deadline) error = %v", err) + } + if !found.LastSeenAt.Equal(touchedAt) { + t.Fatalf("LastSeenAt = %v, want %v", found.LastSeenAt, touchedAt) + } + idleAt := touchedAt.Add(sessionIdleTimeout) + if _, err := sessions.FindActive(ctx, raw.Hash(), idleAt, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(idle) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Touch(ctx, session.ID, idleAt, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(idle) error = %v, want ErrSessionNotFound", err) + } + + // Activity never extends the absolute deadline. + if _, err := sessions.FindActive(ctx, raw.Hash(), session.ExpiresAt, sessionLifetime); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(at absolute deadline) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Touch(ctx, session.ID, session.ExpiresAt, sessionLifetime); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(at absolute deadline) error = %v, want ErrSessionNotFound", err) + } + + unknown, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + if _, err := sessions.FindActive(ctx, unknown.Hash(), fixture.now, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(unknown) error = %v, want ErrSessionNotFound", err) + } + + revokedRaw, revokedSession := fixture.startSession(t, user, fixture.now) + if err := sessions.Revoke(ctx, revokedSession.ID, fixture.now.Add(time.Minute)); err != nil { + t.Fatalf("Revoke() error = %v", err) + } + if _, err := sessions.FindActive(ctx, revokedRaw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(revoked) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Touch(ctx, revokedSession.ID, fixture.now.Add(time.Minute), sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(revoked) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Revoke(ctx, revokedSession.ID, fixture.now.Add(time.Minute)); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("second Revoke() error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Revoke(ctx, uuid.New(), fixture.now); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Revoke(unknown) error = %v, want ErrSessionNotFound", err) + } + }) + + t.Run("revoking all of a user's sessions leaves other users signed in", func(t *testing.T) { + reset(t) + sessions := fixture.store.Sessions() + user := fixture.createUser(t, "everywhere@example.com", domain.ScenarioCandidate, fixture.now) + other := fixture.createUser(t, "bystander@example.com", domain.ScenarioEmployer, fixture.now) + userTokens := make([]domain.SecretToken, 0, signedInSessions) + for range signedInSessions { + raw, _ := fixture.startSession(t, user, fixture.now) + userTokens = append(userTokens, raw) + } + _, alreadyRevoked := fixture.startSession(t, user, fixture.now) + if err := sessions.Revoke(ctx, alreadyRevoked.ID, fixture.now); err != nil { + t.Fatalf("Revoke() error = %v", err) + } + otherRaw, _ := fixture.startSession(t, other, fixture.now) + + revoked, err := sessions.RevokeAllForUser(ctx, user.ID, fixture.now.Add(time.Minute)) + if err != nil { + t.Fatalf("RevokeAllForUser() error = %v", err) + } + if revoked != int64(len(userTokens)) { + t.Fatalf("RevokeAllForUser() = %d, want %d", revoked, len(userTokens)) + } + for _, raw := range userTokens { + if _, err := sessions.FindActive(ctx, raw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(revoked by RevokeAllForUser) error = %v, want ErrSessionNotFound", err) + } + } + if _, err := sessions.FindActive(ctx, otherRaw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout); err != nil { + t.Fatalf("FindActive(other user) error = %v", err) + } + }) + + t.Run("cleanup deletes stale unverified accounts in batches with their tokens and sessions", func(t *testing.T) { + reset(t) + users := fixture.store.Users() + cutoff := fixture.now.Add(-7 * 24 * time.Hour) + stale := make([]domain.User, 0, staleAccounts) + for index := range staleAccounts { + registeredAt := cutoff.Add(-time.Duration(staleAccounts-index) * time.Hour) + user := fixture.createUser(t, fmt.Sprintf("stale%d@example.com", index), domain.ScenarioCandidate, registeredAt) + fixture.issueToken(t, user, registeredAt, tokenLifetime) + fixture.startSession(t, user, registeredAt) + stale = append(stale, user) + } + recent := fixture.createUser(t, "recent@example.com", domain.ScenarioCandidate, cutoff.Add(time.Hour)) + verified := fixture.createUser(t, "verified@example.com", domain.ScenarioCandidate, cutoff.Add(-24*time.Hour)) + if _, err := users.MarkEmailVerified(ctx, verified.ID, verified.RegistrationVersion, cutoff.Add(-23*time.Hour)); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + fixture.startSession(t, verified, fixture.now) + + deleted, err := users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, cleanupBatch) + if err != nil || deleted != cleanupBatch { + t.Fatalf("first DeleteUnverifiedRegisteredBefore() = %d, %v, want 2", deleted, err) + } + // The oldest go first. + for _, user := range stale[:cleanupBatch] { + if _, err := users.GetByID(ctx, user.ID); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(deleted) error = %v, want ErrUserNotFound", err) + } + } + deleted, err = users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, cleanupBatch) + if err != nil || deleted != staleAccounts-cleanupBatch { + t.Fatalf("second DeleteUnverifiedRegisteredBefore() = %d, %v, want 1", deleted, err) + } + for _, kept := range []domain.User{recent, verified} { + if _, err := users.GetByID(ctx, kept.ID); err != nil { + t.Fatalf("GetByID(kept) error = %v", err) + } + } + assertRowCount(ctx, t, pool, usersTable, 2) + assertRowCount(ctx, t, pool, emailTokensTable, 0) + assertRowCount(ctx, t, pool, sessionsTable, 1) + }) + + t.Run("deleting an account cascades to its tokens and sessions", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "cascade@example.com", domain.ScenarioCandidate, fixture.now) + other := fixture.createUser(t, "survivor@example.com", domain.ScenarioCandidate, fixture.now) + for _, owner := range []domain.User{user, other} { + fixture.issueToken(t, owner, fixture.now, tokenLifetime) + fixture.startSession(t, owner, fixture.now) + } + if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, user.ID); err != nil { + t.Fatalf("delete user: %v", err) + } + assertRowCount(ctx, t, pool, emailTokensTable, 1) + assertRowCount(ctx, t, pool, sessionsTable, 1) + var orphans int + err := pool.QueryRow(ctx, ` + SELECT (SELECT count(*) FROM email_tokens WHERE user_id = $1) + + (SELECT count(*) FROM sessions WHERE user_id = $1)`, user.ID).Scan(&orphans) + if err != nil || orphans != 0 { + t.Fatalf("rows of the deleted user = %d, %v, want 0", orphans, err) + } + }) + + t.Run("repositories commit and roll back with the surrounding transaction", func(t *testing.T) { + reset(t) + writeAll := func(user domain.User) func(context.Context, outbound.UnitOfWork) error { + return func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Users().Create(ctx, user); err != nil { + return err + } + _, token := fixture.newToken(t, user, fixture.now, tokenLifetime) + if err := unit.EmailTokens().Insert(ctx, token); err != nil { + return err + } + _, session := fixture.newSession(t, user, fixture.now) + if err := unit.Sessions().Create(ctx, session); err != nil { + return err + } + // Reads inside the transaction see its own writes. + if _, err := unit.Users().GetByID(ctx, user.ID); err != nil { + return err + } + return nil + } + } + + rolledBack := fixture.newUser(t, "rollback@example.com", domain.ScenarioCandidate, fixture.now) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := writeAll(rolledBack)(ctx, unit); err != nil { + return err + } + return errForcedRollback + }) + if !errors.Is(err, errForcedRollback) { + t.Fatalf("WithinTransaction() error = %v, want the callback error", err) + } + for _, table := range identityTables { + assertRowCount(ctx, t, pool, table, 0) + } + + committed := fixture.newUser(t, "commit@example.com", domain.ScenarioCandidate, fixture.now) + if err := transactor.WithinTransaction(ctx, writeAll(committed)); err != nil { + t.Fatalf("WithinTransaction() error = %v", err) + } + for _, table := range identityTables { + assertRowCount(ctx, t, pool, table, 1) + } + + // A failed statement aborts the transaction: the duplicate email rolls + // back the account written before it. + first := fixture.newUser(t, "first@example.com", domain.ScenarioCandidate, fixture.now) + duplicate := fixture.newUser(t, "COMMIT@example.com", domain.ScenarioCandidate, fixture.now) + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Users().Create(ctx, first); err != nil { + return err + } + return unit.Users().Create(ctx, duplicate) + }) + if !errors.Is(err, outbound.ErrEmailTaken) { + t.Fatalf("WithinTransaction(duplicate) error = %v, want ErrEmailTaken", err) + } + if _, err := fixture.store.Users().GetByID(ctx, first.ID); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(rolled back) error = %v, want ErrUserNotFound", err) + } + assertNoBusyConnections(t, pool) + }) + + t.Run("touch writes at most once per interval and reports inactive sessions", func(t *testing.T) { + reset(t) + sessions := fixture.store.Sessions() + user := fixture.createUser(t, "throttle@example.com", domain.ScenarioCandidate, fixture.now) + raw, session := fixture.startSession(t, user, fixture.now) + lastSeen := func(at time.Time) time.Time { + t.Helper() + found, err := sessions.FindActive(ctx, raw.Hash(), at, sessionIdleTimeout) + if err != nil { + t.Fatalf("FindActive() error = %v", err) + } + return found.LastSeenAt + } + soon := fixture.now.Add(30 * time.Second) + if err := sessions.Touch(ctx, session.ID, soon, sessionIdleTimeout); err != nil { + t.Fatalf("Touch(within interval) error = %v", err) + } + if got := lastSeen(soon); !got.Equal(fixture.now) { + t.Fatalf("LastSeenAt after a touch within the interval = %v, want the unchanged %v", got, fixture.now) + } + later := fixture.now.Add(2 * time.Minute) + if err := sessions.Touch(ctx, session.ID, later, sessionIdleTimeout); err != nil { + t.Fatalf("Touch(after interval) error = %v", err) + } + if got := lastSeen(later); !got.Equal(later) { + t.Fatalf("LastSeenAt after a touch past the interval = %v, want %v", got, later) + } + if err := sessions.Touch(ctx, uuid.New(), later, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(unknown) error = %v, want ErrSessionNotFound", err) + } + }) + + t.Run("a waiting consume fails after the holder commits and succeeds after it rolls back", func(t *testing.T) { + for _, variant := range []struct { + name string + commitFirst bool + wantSecond error + }{ + {name: "commit", commitFirst: true, wantSecond: outbound.ErrEmailTokenConsumed}, + {name: "rollback", commitFirst: false, wantSecond: nil}, + } { + t.Run(variant.name, func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "lockwait@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + applicationName := "identity_consume_waiter_" + variant.name + holder := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, fixture.now) + return err + }, variant.commitFirst) + holder.awaitHeld(ctx, t) + + var waiterErr error + waiterDone := make(chan struct{}) + go func() { + defer close(waiterDone) + waiterErr = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + // Label the session so the test can observe its lock wait. + if _, err := integrationTx(t, unit).Exec(ctx, "SET LOCAL application_name = '"+applicationName+"'"); err != nil { + return fmt.Errorf("label waiter: %w", err) + } + _, err := unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, fixture.now) + return err + }) + }() + waitEvent, observed := waitForLockWait(ctx, pool, applicationName) + holderErr := holder.finish() + <-waiterDone + if !observed { + t.Fatalf("the second consume was not observed waiting on a lock (last wait event %q)", waitEvent) + } + t.Logf("observed the second consume waiting on a lock: wait_event=%s", waitEvent) + if variant.commitFirst && holderErr != nil { + t.Fatalf("holder error = %v, want a commit", holderErr) + } + if !variant.commitFirst && !errors.Is(holderErr, errForcedRollback) { + t.Fatalf("holder error = %v, want the forced rollback", holderErr) + } + if (variant.wantSecond == nil && waiterErr != nil) || !errors.Is(waiterErr, variant.wantSecond) { + t.Fatalf("second consume error = %v, want %v", waiterErr, variant.wantSecond) + } + var consumed int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM email_tokens WHERE consumed_at IS NOT NULL`).Scan(&consumed); err != nil || consumed != 1 { + t.Fatalf("consumed tokens = %d, %v, want exactly 1", consumed, err) + } + }) + } + }) + + t.Run("a token issued before a concurrent re-registration cannot verify the new credentials", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "race@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + at := fixture.now.Add(time.Minute) + + // The confirmation consumes the token, holds its transaction open, and + // verifies the account with the token's registration version on finish. + var token domain.EmailToken + confirmation := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + token, err = unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, at) + return err + }, true) + confirmation.afterRelease = func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.Users().MarkEmailVerified(ctx, token.UserID, token.RegistrationVersion, at) + return err + } + confirmation.awaitHeld(ctx, t) + + // The re-registration commits between Consume and MarkEmailVerified. It + // skips InvalidateActive on purpose, so only the version check in + // MarkEmailVerified stands between the old token and the new password. + reRegistered, err := user.ReRegister(fixture.registration(t, "race@example.com", domain.ScenarioEmployer, at)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + stored, err := fixture.store.Users().UpdateRegistration(ctx, reRegistered) + if err != nil { + t.Fatalf("UpdateRegistration() error = %v", err) + } + if err := confirmation.finish(); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("confirmation error = %v, want ErrUserVersionConflict", err) + } + current, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + if current.EmailVerified() || current.RegistrationVersion != stored.RegistrationVersion || current.Scenario != domain.ScenarioEmployer { + t.Fatalf("account after the race = %+v, want the unverified re-registration", current) + } + // The rollback restored the token, which is now superseded. + assertConsumeError(ctx, t, fixture.store.EmailTokens(), raw, at, outbound.ErrEmailTokenInvalidated) + }) + + t.Run("cleanup skips accounts locked by open transactions without waiting", func(t *testing.T) { + reset(t) + cutoff := fixture.now.Add(-7 * 24 * time.Hour) + registeredAt := cutoff.Add(-time.Hour) + reRegistering := fixture.createUser(t, "reregistering@example.com", domain.ScenarioCandidate, registeredAt) + confirming := fixture.createUser(t, "confirming@example.com", domain.ScenarioCandidate, registeredAt) + idle := fixture.createUser(t, "idle@example.com", domain.ScenarioCandidate, registeredAt) + confirmingToken, _ := fixture.issueToken(t, confirming, registeredAt, tokenLifetime) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + + // One transaction holds the account row, the other only a token row. + changed, err := reRegistering.ReRegister(fixture.registration(t, "reregistering@example.com", domain.ScenarioEmployer, fixture.now)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + accountHolder := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.Users().UpdateRegistration(ctx, changed) + return err + }, false) + accountHolder.awaitHeld(ctx, t) + tokenHolder := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.EmailTokens().Consume(ctx, confirmingToken.Hash(), domain.EmailTokenPurposeEmailVerification, registeredAt.Add(time.Minute)) + return err + }, false) + tokenHolder.awaitHeld(ctx, t) + + // A lock wait longer than the timeout would fail the statement. + impatientPool := env.newPoolWithLockTimeout(ctx, t, cleanupLockTimeout) + var lockTimeout string + if err := impatientPool.QueryRow(ctx, "SHOW lock_timeout").Scan(&lockTimeout); err != nil || lockTimeout != fmt.Sprintf("%dms", cleanupLockTimeout.Milliseconds()) { + t.Fatalf("cleanup session lock_timeout = %q, %v, want %s", lockTimeout, err, cleanupLockTimeout) + } + impatientStore := postgresadapter.NewIdentityStore(impatientPool) + deleted, err := impatientStore.Users().DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil { + t.Fatalf("DeleteUnverifiedRegisteredBefore() with locked accounts error = %v", err) + } + if deleted != 1 { + t.Fatalf("DeleteUnverifiedRegisteredBefore() = %d, want only the unlocked account", deleted) + } + if _, err := fixture.store.Users().GetByID(ctx, idle.ID); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(unlocked stale account) error = %v, want ErrUserNotFound", err) + } + if err := accountHolder.finish(); !errors.Is(err, errForcedRollback) { + t.Fatalf("account holder error = %v, want the forced rollback", err) + } + if err := tokenHolder.finish(); !errors.Is(err, errForcedRollback) { + t.Fatalf("token holder error = %v, want the forced rollback", err) + } + + // Once the locks are gone, the next run removes the skipped accounts. + deleted, err = impatientStore.Users().DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil || deleted != 2 { + t.Fatalf("second DeleteUnverifiedRegisteredBefore() = %d, %v, want 2", deleted, err) + } + for _, table := range identityTables { + assertRowCount(ctx, t, pool, table, 0) + } + }) + + t.Run("pool repositories refuse a transaction context", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "nested@example.com", domain.ScenarioCandidate, fixture.now) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, _ outbound.UnitOfWork) error { + _, err := fixture.store.Users().GetByID(ctx, user.ID) + return err + }) + if !errors.Is(err, outbound.ErrNestedTransaction) { + t.Fatalf("IdentityStore inside WithinTransaction error = %v, want ErrNestedTransaction", err) + } + }) + + t.Run("the transactor reports a deadlock as a retryable conflict", func(t *testing.T) { + reset(t) + first := fixture.createUser(t, "deadlock1@example.com", domain.ScenarioCandidate, fixture.now) + second := fixture.createUser(t, "deadlock2@example.com", domain.ScenarioCandidate, fixture.now) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + // Each transaction locks one account and then the other's. + crossLock := func(own, other uuid.UUID, locked chan<- struct{}, otherLocked <-chan struct{}) transactionFn { + return func(ctx context.Context, unit outbound.UnitOfWork) error { + update := `UPDATE users SET updated_at = updated_at WHERE id = $1` + if _, err := integrationTx(t, unit).Exec(ctx, update, own); err != nil { + return err + } + close(locked) + <-otherLocked + _, err := integrationTx(t, unit).Exec(ctx, update, other) + return err + } + } + firstLocked, secondLocked := make(chan struct{}), make(chan struct{}) + errs := make([]error, 2) + var group sync.WaitGroup + group.Go(func() { + errs[0] = concurrentTransactor.WithinTransaction(ctx, crossLock(first.ID, second.ID, firstLocked, secondLocked)) + }) + group.Go(func() { + errs[1] = concurrentTransactor.WithinTransaction(ctx, crossLock(second.ID, first.ID, secondLocked, firstLocked)) + }) + group.Wait() + conflicts := 0 + for index, err := range errs { + switch { + case err == nil: + case errors.Is(err, outbound.ErrTransactionConflict): + conflicts++ + default: + t.Fatalf("transaction %d error = %v, want nil or ErrTransactionConflict", index, err) + } + } + if conflicts != 1 { + t.Fatalf("%d transactions reported a conflict, want exactly 1: %v", conflicts, errs) + } + }) + + t.Run("database constraints back the domain rules", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "constraints@example.com", domain.ScenarioCandidate, fixture.now) + tests := []struct { + constraint string + statement string + args []any + }{ + { + constraint: "users_scenario_onboarding_step", + statement: `UPDATE users SET onboarding_step = 'employer_company' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_scenario_onboarding_step", + statement: `UPDATE users SET scenario = 'admin' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_password_hash_format", + statement: `UPDATE users SET password_hash = 'correct horse battery staple' WHERE id = $1`, + args: []any{user.ID}, + }, + { + // The key matches the address, so only the ASCII rule fails. + constraint: "users_email_ascii", + statement: "UPDATE users SET email = 'Jos\u00e9@example.com', email_normalized = 'jos\u00e9@example.com' WHERE id = $1", + args: []any{user.ID}, + }, + { + constraint: "users_email_normalized_rule", + statement: `UPDATE users SET email_normalized = 'CONSTRAINTS@example.com' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_timestamps_after_creation", + statement: `UPDATE users SET email_verified_at = created_at - interval '1 second' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "email_tokens_outcome_after_creation", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at, consumed_at) + VALUES ($1, $2, 'email_verification', $3, 1, $4, $5, $6)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour), fixture.now.Add(-time.Second)}, + }, + { + constraint: "sessions_revoked_after_creation", + statement: `INSERT INTO sessions (id, user_id, token_hash, created_at, last_seen_at, expires_at, revoked_at) + VALUES ($1, $2, $3, $4, $4, $5, $6)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour), fixture.now.Add(-time.Second)}, + }, + { + constraint: "email_tokens_token_hash_sha256", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at) + VALUES ($1, $2, 'email_verification', $3, 1, $4, $5)`, + args: []any{uuid.New(), user.ID, []byte("raw-token-is-not-a-digest"), fixture.now, fixture.now.Add(time.Hour)}, + }, + { + constraint: "email_tokens_purpose_known", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at) + VALUES ($1, $2, 'magic_link', $3, 1, $4, $5)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour)}, + }, + { + constraint: "email_tokens_single_outcome", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at, consumed_at, invalidated_at) + VALUES ($1, $2, 'email_verification', $3, 1, $4, $5, $4, $4)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour)}, + }, + { + constraint: "sessions_expiry_after_creation", + statement: `INSERT INTO sessions (id, user_id, token_hash, created_at, last_seen_at, expires_at) + VALUES ($1, $2, $3, $4, $4, $4)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now}, + }, + } + for _, test := range tests { + _, err := pool.Exec(ctx, test.statement, test.args...) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != checkViolationCode || pgError.ConstraintName != test.constraint { + t.Fatalf("statement violating %s error = %v, want a check violation", test.constraint, err) + } + } + }) +} + +func (fixture identityFixture) registration(t *testing.T, rawEmail string, scenario domain.Scenario, at time.Time) domain.Registration { + t.Helper() + passwordHash, err := domain.NewPasswordHash(identityTestPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + return domain.Registration{Email: mustEmail(t, rawEmail), PasswordHash: passwordHash, Scenario: scenario, RegisteredAt: at} +} + +func (fixture identityFixture) newUser(t *testing.T, rawEmail string, scenario domain.Scenario, at time.Time) domain.User { + t.Helper() + user, err := domain.NewUser(fixture.registration(t, rawEmail, scenario, at)) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + return user +} + +func (fixture identityFixture) createUser(t *testing.T, rawEmail string, scenario domain.Scenario, at time.Time) domain.User { + t.Helper() + user := fixture.newUser(t, rawEmail, scenario, at) + if err := fixture.store.Users().Create(fixture.ctx, user); err != nil { + t.Fatalf("Create(%s) error = %v", rawEmail, err) + } + return user +} + +func (fixture identityFixture) newToken(t *testing.T, user domain.User, at time.Time, lifetime time.Duration) (domain.SecretToken, domain.EmailToken) { + t.Helper() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ + UserID: user.ID, Purpose: domain.EmailTokenPurposeEmailVerification, TokenHash: raw.Hash(), + RegistrationVersion: user.RegistrationVersion, IssuedAt: at, Lifetime: lifetime, + }) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + return raw, token +} + +func (fixture identityFixture) issueToken(t *testing.T, user domain.User, at time.Time, lifetime time.Duration) (domain.SecretToken, domain.EmailToken) { + t.Helper() + raw, token := fixture.newToken(t, user, at, lifetime) + if err := fixture.store.EmailTokens().Insert(fixture.ctx, token); err != nil { + t.Fatalf("Insert() error = %v", err) + } + return raw, token +} + +func (fixture identityFixture) newSession(t *testing.T, user domain.User, at time.Time) (domain.SecretToken, domain.Session) { + t.Helper() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + session, err := domain.NewSession(domain.NewSessionInput{ + UserID: user.ID, TokenHash: raw.Hash(), StartedAt: at, AbsoluteLifetime: sessionLifetime, + }) + if err != nil { + t.Fatalf("NewSession() error = %v", err) + } + return raw, session +} + +func (fixture identityFixture) startSession(t *testing.T, user domain.User, at time.Time) (domain.SecretToken, domain.Session) { + t.Helper() + raw, session := fixture.newSession(t, user, at) + if err := fixture.store.Sessions().Create(fixture.ctx, session); err != nil { + t.Fatalf("Create(session) error = %v", err) + } + return raw, session +} + +func mustEmail(t *testing.T, raw string) domain.EmailAddress { + t.Helper() + email, err := domain.NewEmailAddress(raw) + if err != nil { + t.Fatalf("NewEmailAddress(%q) error = %v", raw, err) + } + return email +} + +func assertConsumeError( + ctx context.Context, + t *testing.T, + tokens outbound.EmailTokenRepository, + raw domain.SecretToken, + at time.Time, + want error, +) { + t.Helper() + if _, err := tokens.Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, at); !errors.Is(err, want) { + t.Fatalf("Consume() error = %v, want %v", err, want) + } +} + +func assertSameUser(t *testing.T, got, want domain.User) { + t.Helper() + sameVerification := (got.EmailVerifiedAt == nil) == (want.EmailVerifiedAt == nil) && + (got.EmailVerifiedAt == nil || got.EmailVerifiedAt.Equal(*want.EmailVerifiedAt)) + if got.ID != want.ID || got.Email != want.Email || got.PasswordHash.PHC() != want.PasswordHash.PHC() || + got.Scenario != want.Scenario || got.OnboardingStep != want.OnboardingStep || !sameVerification || + got.RegistrationVersion != want.RegistrationVersion || !got.LastRegisteredAt.Equal(want.LastRegisteredAt) || + got.Version != want.Version || !got.CreatedAt.Equal(want.CreatedAt) || !got.UpdatedAt.Equal(want.UpdatedAt) { + t.Fatalf("user = %+v, want %+v", got, want) + } +} + +func assertSameSession(t *testing.T, got, want domain.Session) { + t.Helper() + if got.ID != want.ID || got.UserID != want.UserID || got.TokenHash != want.TokenHash || + !got.CreatedAt.Equal(want.CreatedAt) || !got.LastSeenAt.Equal(want.LastSeenAt) || + !got.ExpiresAt.Equal(want.ExpiresAt) || got.RevokedAt != nil { + t.Fatalf("session = %+v, want %+v", got, want) + } +} + +func assertRowCount(ctx context.Context, t *testing.T, pool *pgxpool.Pool, table pgx.Identifier, want int) { + t.Helper() + var count int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM "+table.Sanitize()).Scan(&count); err != nil { + t.Fatalf("count rows in %s: %v", table.Sanitize(), err) + } + if count != want { + t.Fatalf("%s has %d rows, want %d", table.Sanitize(), count, want) + } +} + +// heldTransaction runs work in a transaction and keeps the transaction open +// until finish, so a test can act while its locks are held. +type heldTransaction struct { + held chan struct{} + release chan struct{} + finished chan struct{} + once sync.Once + err error + // afterRelease, when set before awaitHeld returns, runs in the same + // transaction after finish releases it. + afterRelease transactionFn +} + +// startHeldTransaction runs work in a transaction and then holds it open. +// After finish, the transaction runs afterRelease and commits when commit is +// true, or rolls back with errForcedRollback otherwise. +func startHeldTransaction( + ctx context.Context, + t *testing.T, + transactor outbound.Transactor, + work transactionFn, + commit bool, +) *heldTransaction { + t.Helper() + holder := &heldTransaction{ + held: make(chan struct{}), + release: make(chan struct{}), + finished: make(chan struct{}), + } + t.Cleanup(func() { _ = holder.finish() }) + go func() { + defer close(holder.finished) + holder.err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := work(ctx, unit); err != nil { + return err + } + close(holder.held) + select { + case <-holder.release: + case <-ctx.Done(): + return ctx.Err() + } + if holder.afterRelease != nil { + if err := holder.afterRelease(ctx, unit); err != nil { + return err + } + } + if !commit { + return errForcedRollback + } + return nil + }) + }() + return holder +} + +func (holder *heldTransaction) awaitHeld(ctx context.Context, t *testing.T) { + t.Helper() + select { + case <-holder.held: + case <-holder.finished: + t.Fatalf("held transaction finished before holding its locks: %v", holder.err) + case <-ctx.Done(): + t.Fatalf("wait for the held transaction: %v", ctx.Err()) + } +} + +// finish releases the transaction and returns its result. +func (holder *heldTransaction) finish() error { + holder.once.Do(func() { close(holder.release) }) + <-holder.finished + return holder.err +} diff --git a/backend/integration_test/postgres_helpers_test.go b/backend/integration_test/postgres_helpers_test.go index bfb9970..d66dcec 100644 --- a/backend/integration_test/postgres_helpers_test.go +++ b/backend/integration_test/postgres_helpers_test.go @@ -7,8 +7,10 @@ import ( "crypto/rand" "io/fs" "net/url" + "strconv" "strings" "testing" + "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" @@ -95,6 +97,23 @@ func (env *testEnvironment) newPoolWithMaxConns(ctx context.Context, t *testing. return pool } +// newPoolWithLockTimeout opens a pool whose sessions fail a lock wait after +// timeout, so a test can prove that a statement never waits for a lock. +func (env *testEnvironment) newPoolWithLockTimeout(ctx context.Context, t *testing.T, timeout time.Duration) *pgxpool.Pool { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + poolConfig.ConnConfig.RuntimeParams["lock_timeout"] = strconv.FormatInt(timeout.Milliseconds(), 10) + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create PostgreSQL pool with a lock timeout: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + // createIsolatedDatabase creates an empty database in the bootstrap container // for tests that must change the whole schema, and drops it with t. func (env *testEnvironment) createIsolatedDatabase(ctx context.Context, t *testing.T) string { diff --git a/backend/integration_test/postgres_migrations_test.go b/backend/integration_test/postgres_migrations_test.go index 137fef2..9e18b5d 100644 --- a/backend/integration_test/postgres_migrations_test.go +++ b/backend/integration_test/postgres_migrations_test.go @@ -19,6 +19,15 @@ const ( concurrentMigrators = 4 ) +// identityMigrationVersion creates identityTableNames. +const identityMigrationVersion = 2 + +var ( + // Tables created by 00001 and by 00002. + outboxTables = []string{"outbox_events"} + identityTableNames = []string{"users", "email_tokens", "sessions"} +) + func TestPostgresMigrations(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) @@ -41,10 +50,12 @@ func TestPostgresMigrations(t *testing.T) { if len(applied) != total { t.Fatalf("first Up() applied %d migrations, want %d", len(applied), total) } - assertOutboxTableExists(ctx, t, pool, true) + assertTablesExist(ctx, t, pool, true, outboxTables...) + assertTablesExist(ctx, t, pool, true, identityTableNames...) + identityRolledBack := false for rolledBack := 0; ; rolledBack++ { - _, err := migrator.DownOne(ctx) + result, err := migrator.DownOne(ctx) if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) { if rolledBack != total { t.Fatalf("rolled back %d migrations, want %d", rolledBack, total) @@ -54,8 +65,19 @@ func TestPostgresMigrations(t *testing.T) { if err != nil { t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err) } + if result.Version == identityMigrationVersion { + // The identity migration rolls back on its own and leaves the + // outbox migration before it. + assertTablesExist(ctx, t, pool, false, identityTableNames...) + assertTablesExist(ctx, t, pool, true, outboxTables...) + identityRolledBack = true + } } - assertOutboxTableExists(ctx, t, pool, false) + if !identityRolledBack { + t.Fatalf("migration %d was not rolled back", identityMigrationVersion) + } + assertTablesExist(ctx, t, pool, false, outboxTables...) + assertTablesExist(ctx, t, pool, false, identityTableNames...) var leftovers int err = pool.QueryRow(ctx, ` SELECT count(*) FROM pg_catalog.pg_class AS c @@ -75,7 +97,8 @@ func TestPostgresMigrations(t *testing.T) { if len(applied) != total { t.Fatalf("second Up() applied %d migrations, want %d", len(applied), total) } - assertOutboxTableExists(ctx, t, pool, true) + assertTablesExist(ctx, t, pool, true, outboxTables...) + assertTablesExist(ctx, t, pool, true, identityTableNames...) assertAllApplied(ctx, t, migrator, total) }) @@ -129,13 +152,15 @@ func assertAllApplied(ctx context.Context, t *testing.T, migrator *postgresadapt } } -func assertOutboxTableExists(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool) { +func assertTablesExist(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool, tables ...string) { t.Helper() - var exists bool - if err := pool.QueryRow(ctx, `SELECT to_regclass('public.outbox_events') IS NOT NULL`).Scan(&exists); err != nil { - t.Fatalf("check outbox table: %v", err) - } - if exists != want { - t.Fatalf("outbox_events exists = %t, want %t", exists, want) + for _, table := range tables { + var exists bool + if err := pool.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, "public."+table).Scan(&exists); err != nil { + t.Fatalf("check table %s: %v", table, err) + } + if exists != want { + t.Fatalf("%s exists = %t, want %t", table, exists, want) + } } } diff --git a/backend/internal/adapter/secondary/postgres/database_error.go b/backend/internal/adapter/secondary/postgres/database_error.go new file mode 100644 index 0000000..7fe352f --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/database_error.go @@ -0,0 +1,54 @@ +package postgres + +import ( + "errors" + "fmt" + + "lincodex/backend/internal/port/outbound" +) + +const ( + deadlockDetectedCode = "40P01" + serializationFailureCode = "40001" +) + +// databaseError keeps only the SQLSTATE and constraint name of a PostgreSQL +// error. The message and detail of a pgconn.PgError can quote row values, such +// as an email address or a password hash, so repositories that handle +// personal data return this type instead. +type databaseError struct { + code string + constraint string +} + +func (err *databaseError) Error() string { + if err.constraint == "" { + return "PostgreSQL error SQLSTATE " + err.code + } + return "PostgreSQL error SQLSTATE " + err.code + " on constraint " + err.constraint +} + +// SQLState matches the method of pgconn.PgError, so callers can read the code +// from either type. +func (err *databaseError) SQLState() string { return err.code } + +// sqlStateError is implemented by pgconn.PgError and databaseError. +type sqlStateError interface { + error + SQLState() string +} + +// markTransactionConflict makes a deadlock or serialization failure also +// match outbound.ErrTransactionConflict and returns other errors unchanged. +func markTransactionConflict(err error) error { + var stateError sqlStateError + if err == nil || errors.Is(err, outbound.ErrTransactionConflict) || !errors.As(err, &stateError) { + return err + } + switch code := stateError.SQLState(); code { + case deadlockDetectedCode, serializationFailureCode: + return fmt.Errorf("postgres.markTransactionConflict - SQLSTATE %s: %w: %w", code, outbound.ErrTransactionConflict, err) + default: + return err + } +} diff --git a/backend/internal/adapter/secondary/postgres/identity.go b/backend/internal/adapter/secondary/postgres/identity.go new file mode 100644 index 0000000..f2234a9 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/identity.go @@ -0,0 +1,566 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "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" +) + +// PostgreSQL stores timestamps with microsecond precision, so a stored time +// is the written time truncated to microseconds. + +const ( + foreignKeyViolationCode = "23503" + + // sessionTouchInterval is the minimum age of last_seen_at before Touch + // writes it again. It bounds session writes to one per minute per session + // at the cost of ending an idle session up to a minute early. + sessionTouchInterval = time.Minute +) + +type constraintViolation struct { + code string + constraint string +} + +// identityConstraintErrors maps the identity constraints whose violation is a +// caller-visible outcome to port sentinels. Matching uses SQLSTATE and the +// constraint name from the migration, never the error text. +var identityConstraintErrors = map[constraintViolation]error{ + {uniqueViolationCode, "users_email_normalized_key"}: outbound.ErrEmailTaken, + {uniqueViolationCode, "email_tokens_token_hash_key"}: outbound.ErrTokenHashConflict, + {uniqueViolationCode, "sessions_token_hash_key"}: outbound.ErrTokenHashConflict, + {foreignKeyViolationCode, "email_tokens_user_id_fkey"}: outbound.ErrUserNotFound, + {foreignKeyViolationCode, "sessions_user_id_fkey"}: outbound.ErrUserNotFound, +} + +// mapIdentityError turns a known identity constraint violation into its port +// sentinel and keeps the constraint name. Any other PostgreSQL error is +// replaced by its SQLSTATE and constraint name, because its message and +// detail can quote row values such as an email address or a password hash. +// Deadlocks and serialization failures also match ErrTransactionConflict. +// Errors that do not come from PostgreSQL pass through. +func mapIdentityError(err error) error { + var pgError *pgconn.PgError + if !errors.As(err, &pgError) { + return err + } + if sentinel, ok := identityConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok { + return fmt.Errorf("postgres.mapIdentityError - violate constraint %s: %w", pgError.ConstraintName, sentinel) + } + return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}) +} + +// IdentityStore provides the identity repositories outside a transaction. +// Every call runs as its own statement on a pool connection. A call with a +// context that belongs to a Transactor callback fails with +// outbound.ErrNestedTransaction instead of committing independently of that +// transaction; use the UnitOfWork accessors there. +type IdentityStore struct { + queries *sqlc.Queries +} + +func NewIdentityStore(pool *pgxpool.Pool) *IdentityStore { + return &IdentityStore{queries: sqlc.New(standaloneDB{pool: pool})} +} + +var ( + _ outbound.IdentityRepositories = (*IdentityStore)(nil) + _ outbound.IdentityRepositories = (*UnitOfWork)(nil) +) + +func (store *IdentityStore) Users() outbound.UserRepository { + return userRepository{queries: store.queries} +} + +func (store *IdentityStore) EmailTokens() outbound.EmailTokenRepository { + return emailTokenRepository{queries: store.queries} +} + +func (store *IdentityStore) Sessions() outbound.SessionRepository { + return sessionRepository{queries: store.queries} +} + +func (unit *UnitOfWork) Users() outbound.UserRepository { + return userRepository{queries: unit.queries} +} + +func (unit *UnitOfWork) EmailTokens() outbound.EmailTokenRepository { + return emailTokenRepository{queries: unit.queries} +} + +func (unit *UnitOfWork) Sessions() outbound.SessionRepository { + return sessionRepository{queries: unit.queries} +} + +// standaloneDB runs statements on the pool and refuses a context that belongs +// to a Transactor callback, where a pool statement would silently bypass the +// surrounding transaction. +type standaloneDB struct { + pool *pgxpool.Pool +} + +func (db standaloneDB) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) { + if err := refuseTransactionContext(ctx); err != nil { + return pgconn.CommandTag{}, err + } + return db.pool.Exec(ctx, sql, arguments...) +} + +func (db standaloneDB) Query(ctx context.Context, sql string, arguments ...any) (pgx.Rows, error) { + if err := refuseTransactionContext(ctx); err != nil { + return nil, err + } + return db.pool.Query(ctx, sql, arguments...) +} + +func (db standaloneDB) QueryRow(ctx context.Context, sql string, arguments ...any) pgx.Row { + if err := refuseTransactionContext(ctx); err != nil { + return errorRow{err: err} + } + return db.pool.QueryRow(ctx, sql, arguments...) +} + +func refuseTransactionContext(ctx context.Context) error { + if ctx.Value(transactionContextKey{}) != nil { + return fmt.Errorf("postgres.refuseTransactionContext - run a pool statement inside a transaction callback: %w", outbound.ErrNestedTransaction) + } + return nil +} + +// errorRow reports err from Scan, as pgx does for a failed QueryRow. +type errorRow struct { + err error +} + +func (row errorRow) Scan(...any) error { return row.err } + +// requireTime rejects the zero time, which would make every deadline check +// pass or fail silently. +func requireTime(location string, at time.Time, sentinel error) error { + if at.IsZero() { + return fmt.Errorf("%s - time must be set: %w", location, sentinel) + } + return nil +} + +type userRepository struct { + queries *sqlc.Queries +} + +func (repository userRepository) Create(ctx context.Context, user domain.User) error { + if user.ID == uuid.Nil || user.Email.IsZero() || user.PasswordHash.IsZero() { + return fmt.Errorf("userRepository.Create - user was not built by domain.NewUser: %w", domain.ErrInvalidUser) + } + err := repository.queries.InsertUser(ctx, sqlc.InsertUserParams{ + ID: pgUUID(user.ID), + Email: user.Email.Address(), + EmailNormalized: user.Email.Normalized(), + PasswordHash: user.PasswordHash.PHC(), + Scenario: string(user.Scenario), + OnboardingStep: string(user.OnboardingStep), + EmailVerifiedAt: pgOptionalTime(user.EmailVerifiedAt), + RegistrationVersion: user.RegistrationVersion, + LastRegisteredAt: pgTime(user.LastRegisteredAt), + Version: user.Version, + CreatedAt: pgTime(user.CreatedAt), + UpdatedAt: pgTime(user.UpdatedAt), + }) + if err != nil { + return fmt.Errorf("userRepository.Create - insert user: %w", mapIdentityError(err)) + } + return nil +} + +func (repository userRepository) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) { + row, err := repository.queries.GetUserByID(ctx, pgUUID(id)) + if err != nil { + return domain.User{}, fmt.Errorf("userRepository.GetByID - select user: %w", mapNoRows(err, outbound.ErrUserNotFound)) + } + return userFromRow(row) +} + +func (repository userRepository) GetByEmail(ctx context.Context, email domain.EmailAddress) (domain.User, error) { + row, err := repository.queries.GetUserByEmailNormalized(ctx, email.Normalized()) + if err != nil { + return domain.User{}, fmt.Errorf("userRepository.GetByEmail - select user: %w", mapNoRows(err, outbound.ErrUserNotFound)) + } + return userFromRow(row) +} + +func (repository userRepository) UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error) { + if err := requireTime("userRepository.UpdateRegistration", user.LastRegisteredAt, domain.ErrInvalidUser); err != nil { + return domain.User{}, err + } + row, err := repository.queries.UpdateUserRegistration(ctx, sqlc.UpdateUserRegistrationParams{ + ID: pgUUID(user.ID), + ExpectedVersion: user.Version, + Email: user.Email.Address(), + PasswordHash: user.PasswordHash.PHC(), + Scenario: string(user.Scenario), + OnboardingStep: string(user.OnboardingStep), + LastRegisteredAt: pgTime(user.LastRegisteredAt), + UpdatedAt: pgTime(user.UpdatedAt), + }) + if err != nil { + return domain.User{}, fmt.Errorf("userRepository.UpdateRegistration - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict)) + } + return userFromRow(row) +} + +func (repository userRepository) MarkEmailVerified( + ctx context.Context, + id uuid.UUID, + registrationVersion int64, + at time.Time, +) (domain.User, error) { + if err := requireTime("userRepository.MarkEmailVerified", at, domain.ErrInvalidUser); err != nil { + return domain.User{}, err + } + row, err := repository.queries.MarkUserEmailVerified(ctx, sqlc.MarkUserEmailVerifiedParams{ + ID: pgUUID(id), + RegistrationVersion: registrationVersion, + VerifiedAt: pgTime(at), + }) + if err != nil { + return domain.User{}, fmt.Errorf("userRepository.MarkEmailVerified - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict)) + } + return userFromRow(row) +} + +func (repository userRepository) DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error) { + if err := requireTime("userRepository.DeleteUnverifiedRegisteredBefore", cutoff, domain.ErrInvalidUser); err != nil { + return 0, err + } + if limit <= 0 { + return 0, errors.New("userRepository.DeleteUnverifiedRegisteredBefore - limit must be positive") + } + deleted, err := repository.queries.DeleteUnverifiedUsersRegisteredBefore(ctx, sqlc.DeleteUnverifiedUsersRegisteredBeforeParams{ + Cutoff: pgTime(cutoff), + BatchLimit: limit, + }) + if err != nil { + return 0, fmt.Errorf("userRepository.DeleteUnverifiedRegisteredBefore - delete users: %w", mapIdentityError(err)) + } + return deleted, nil +} + +func userFromRow(row sqlc.User) (domain.User, error) { + email, err := domain.RestoreEmailAddress(row.Email, row.EmailNormalized) + if err != nil { + return domain.User{}, fmt.Errorf("postgres.userFromRow - decode email: %w", err) + } + passwordHash, err := domain.NewPasswordHash(row.PasswordHash) + if err != nil { + return domain.User{}, fmt.Errorf("postgres.userFromRow - decode password hash: %w", err) + } + scenario, err := domain.ParseScenario(row.Scenario) + if err != nil { + return domain.User{}, fmt.Errorf("postgres.userFromRow - decode scenario: %w", err) + } + step, err := domain.ParseOnboardingStep(row.OnboardingStep) + if err != nil { + return domain.User{}, fmt.Errorf("postgres.userFromRow - decode onboarding step: %w", err) + } + return domain.User{ + ID: uuid.UUID(row.ID.Bytes), + Email: email, + PasswordHash: passwordHash, + Scenario: scenario, + OnboardingStep: step, + EmailVerifiedAt: optionalTime(row.EmailVerifiedAt), + RegistrationVersion: row.RegistrationVersion, + LastRegisteredAt: row.LastRegisteredAt.Time, + Version: row.Version, + CreatedAt: row.CreatedAt.Time, + UpdatedAt: row.UpdatedAt.Time, + }, nil +} + +type emailTokenRepository struct { + queries *sqlc.Queries +} + +func (repository emailTokenRepository) Insert(ctx context.Context, token domain.EmailToken) error { + if token.ID == uuid.Nil || token.TokenHash.IsZero() { + return fmt.Errorf("emailTokenRepository.Insert - token was not built by domain.NewEmailToken: %w", domain.ErrInvalidEmailToken) + } + err := repository.queries.InsertEmailToken(ctx, sqlc.InsertEmailTokenParams{ + ID: pgUUID(token.ID), + UserID: pgUUID(token.UserID), + Purpose: string(token.Purpose), + TokenHash: token.TokenHash[:], + RegistrationVersion: token.RegistrationVersion, + CreatedAt: pgTime(token.CreatedAt), + ExpiresAt: pgTime(token.ExpiresAt), + }) + if err != nil { + return fmt.Errorf("emailTokenRepository.Insert - insert email token: %w", mapIdentityError(err)) + } + return nil +} + +func (repository emailTokenRepository) InvalidateActive( + ctx context.Context, + userID uuid.UUID, + purpose domain.EmailTokenPurpose, + at time.Time, +) (int64, error) { + if err := requireTime("emailTokenRepository.InvalidateActive", at, domain.ErrInvalidEmailToken); err != nil { + return 0, err + } + invalidated, err := repository.queries.InvalidateActiveEmailTokens(ctx, sqlc.InvalidateActiveEmailTokensParams{ + UserID: pgUUID(userID), + Purpose: string(purpose), + InvalidatedAt: pgTime(at), + }) + if err != nil { + return 0, fmt.Errorf("emailTokenRepository.InvalidateActive - update email tokens: %w", mapIdentityError(err)) + } + return invalidated, nil +} + +func (repository emailTokenRepository) Consume( + ctx context.Context, + hash domain.SecretTokenHash, + purpose domain.EmailTokenPurpose, + at time.Time, +) (domain.EmailToken, error) { + if err := requireTime("emailTokenRepository.Consume", at, domain.ErrInvalidEmailToken); err != nil { + return domain.EmailToken{}, err + } + row, err := repository.queries.ConsumeEmailToken(ctx, sqlc.ConsumeEmailTokenParams{ + TokenHash: hash[:], + Purpose: string(purpose), + ConsumedAt: pgTime(at), + }) + if err == nil { + return emailTokenFromRow(row) + } + if !errors.Is(err, pgx.ErrNoRows) { + return domain.EmailToken{}, fmt.Errorf("emailTokenRepository.Consume - update email token: %w", mapIdentityError(err)) + } + if err := repository.explainUnconsumable(ctx, hash, purpose, at); err != nil { + return domain.EmailToken{}, fmt.Errorf("emailTokenRepository.Consume - consume email token: %w", err) + } + return domain.EmailToken{}, errors.New("emailTokenRepository.Consume - token became consumable after a failed attempt") +} + +// explainUnconsumable classifies a token that the atomic consume did not +// match. A nil result means the token is consumable again, which only a +// concurrent transaction that changed and then rolled back the row can cause. +func (repository emailTokenRepository) explainUnconsumable( + ctx context.Context, + hash domain.SecretTokenHash, + purpose domain.EmailTokenPurpose, + at time.Time, +) error { + state, err := repository.queries.GetEmailTokenState(ctx, sqlc.GetEmailTokenStateParams{ + TokenHash: hash[:], + Purpose: string(purpose), + }) + if err != nil { + return fmt.Errorf("emailTokenRepository.explainUnconsumable - select token state: %w", mapNoRows(err, outbound.ErrEmailTokenNotFound)) + } + switch { + case state.ConsumedAt.Valid: + return outbound.ErrEmailTokenConsumed + case state.InvalidatedAt.Valid || !state.CurrentRegistration: + return outbound.ErrEmailTokenInvalidated + case !state.ExpiresAt.Time.After(at): + return outbound.ErrEmailTokenExpired + default: + return nil + } +} + +func emailTokenFromRow(row sqlc.EmailToken) (domain.EmailToken, error) { + purpose, err := domain.ParseEmailTokenPurpose(row.Purpose) + if err != nil { + return domain.EmailToken{}, fmt.Errorf("postgres.emailTokenFromRow - decode purpose: %w", err) + } + hash, err := tokenHashFromBytes(row.TokenHash) + if err != nil { + return domain.EmailToken{}, err + } + return domain.EmailToken{ + ID: uuid.UUID(row.ID.Bytes), + UserID: uuid.UUID(row.UserID.Bytes), + Purpose: purpose, + TokenHash: hash, + RegistrationVersion: row.RegistrationVersion, + CreatedAt: row.CreatedAt.Time, + ExpiresAt: row.ExpiresAt.Time, + ConsumedAt: optionalTime(row.ConsumedAt), + InvalidatedAt: optionalTime(row.InvalidatedAt), + }, nil +} + +type sessionRepository struct { + queries *sqlc.Queries +} + +func (repository sessionRepository) Create(ctx context.Context, session domain.Session) error { + if session.ID == uuid.Nil || session.TokenHash.IsZero() { + return fmt.Errorf("sessionRepository.Create - session was not built by domain.NewSession: %w", domain.ErrInvalidSession) + } + err := repository.queries.InsertSession(ctx, sqlc.InsertSessionParams{ + ID: pgUUID(session.ID), + UserID: pgUUID(session.UserID), + TokenHash: session.TokenHash[:], + CreatedAt: pgTime(session.CreatedAt), + LastSeenAt: pgTime(session.LastSeenAt), + ExpiresAt: pgTime(session.ExpiresAt), + }) + if err != nil { + return fmt.Errorf("sessionRepository.Create - insert session: %w", mapIdentityError(err)) + } + return nil +} + +func (repository sessionRepository) FindActive( + ctx context.Context, + hash domain.SecretTokenHash, + at time.Time, + idleTimeout time.Duration, +) (domain.Session, error) { + if err := validateSessionCheck("sessionRepository.FindActive", at, idleTimeout); err != nil { + return domain.Session{}, err + } + row, err := repository.queries.GetActiveSessionByTokenHash(ctx, sqlc.GetActiveSessionByTokenHashParams{ + TokenHash: hash[:], + At: pgTime(at), + IdleCutoff: pgTime(at.Add(-idleTimeout)), + }) + if err != nil { + return domain.Session{}, fmt.Errorf("sessionRepository.FindActive - select session: %w", mapNoRows(err, outbound.ErrSessionNotFound)) + } + return sessionFromRow(row) +} + +func (repository sessionRepository) Touch(ctx context.Context, id uuid.UUID, at time.Time, idleTimeout time.Duration) error { + if err := validateSessionCheck("sessionRepository.Touch", at, idleTimeout); err != nil { + return err + } + result, err := repository.queries.TouchSession(ctx, sqlc.TouchSessionParams{ + ID: pgUUID(id), + At: pgTime(at), + IdleCutoff: pgTime(at.Add(-idleTimeout)), + TouchCutoff: pgTime(at.Add(-sessionTouchInterval)), + }) + if err != nil { + return fmt.Errorf("sessionRepository.Touch - update session: %w", mapIdentityError(err)) + } + if !result.Active { + return fmt.Errorf("sessionRepository.Touch - update session: %w", outbound.ErrSessionNotFound) + } + return nil +} + +func validateSessionCheck(location string, at time.Time, idleTimeout time.Duration) error { + if err := requireTime(location, at, domain.ErrInvalidSession); err != nil { + return err + } + if idleTimeout <= 0 { + return fmt.Errorf("%s - idle timeout must be positive: %w", location, domain.ErrInvalidSession) + } + return nil +} + +func (repository sessionRepository) Revoke(ctx context.Context, id uuid.UUID, at time.Time) error { + if err := requireTime("sessionRepository.Revoke", at, domain.ErrInvalidSession); err != nil { + return err + } + revoked, err := repository.queries.RevokeSession(ctx, sqlc.RevokeSessionParams{ + ID: pgUUID(id), + RevokedAt: pgTime(at), + }) + if err != nil { + return fmt.Errorf("sessionRepository.Revoke - update session: %w", mapIdentityError(err)) + } + if revoked == 0 { + return fmt.Errorf("sessionRepository.Revoke - update session: %w", outbound.ErrSessionNotFound) + } + return nil +} + +func (repository sessionRepository) RevokeAllForUser(ctx context.Context, userID uuid.UUID, at time.Time) (int64, error) { + if err := requireTime("sessionRepository.RevokeAllForUser", at, domain.ErrInvalidSession); err != nil { + return 0, err + } + revoked, err := repository.queries.RevokeUserSessions(ctx, sqlc.RevokeUserSessionsParams{ + UserID: pgUUID(userID), + RevokedAt: pgTime(at), + }) + if err != nil { + return 0, fmt.Errorf("sessionRepository.RevokeAllForUser - update sessions: %w", mapIdentityError(err)) + } + return revoked, nil +} + +func sessionFromRow(row sqlc.Session) (domain.Session, error) { + hash, err := tokenHashFromBytes(row.TokenHash) + if err != nil { + return domain.Session{}, err + } + return domain.Session{ + ID: uuid.UUID(row.ID.Bytes), + UserID: uuid.UUID(row.UserID.Bytes), + TokenHash: hash, + CreatedAt: row.CreatedAt.Time, + LastSeenAt: row.LastSeenAt.Time, + ExpiresAt: row.ExpiresAt.Time, + RevokedAt: optionalTime(row.RevokedAt), + }, nil +} + +func tokenHashFromBytes(stored []byte) (domain.SecretTokenHash, error) { + var hash domain.SecretTokenHash + if len(stored) != len(hash) { + return hash, errors.New("postgres.tokenHashFromBytes - stored token hash is not a SHA-256 digest") + } + copy(hash[:], stored) + return hash, nil +} + +// mapNoRows replaces pgx.ErrNoRows with the port sentinel for a missing or +// unmatched row and maps other errors with mapIdentityError. +func mapNoRows(err, sentinel error) error { + if errors.Is(err, pgx.ErrNoRows) { + return sentinel + } + return mapIdentityError(err) +} + +func pgUUID(id uuid.UUID) pgtype.UUID { + return pgtype.UUID{Bytes: id, Valid: true} +} + +func pgTime(value time.Time) pgtype.Timestamptz { + return pgtype.Timestamptz{Time: value, Valid: true} +} + +func pgOptionalTime(value *time.Time) pgtype.Timestamptz { + if value == nil { + return pgtype.Timestamptz{} + } + return pgTime(*value) +} + +func optionalTime(value pgtype.Timestamptz) *time.Time { + if !value.Valid { + return nil + } + return &value.Time +} diff --git a/backend/internal/adapter/secondary/postgres/identity_test.go b/backend/internal/adapter/secondary/postgres/identity_test.go new file mode 100644 index 0000000..3faa34f --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/identity_test.go @@ -0,0 +1,159 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestMapIdentityErrorRecognizesIdentityConstraints(t *testing.T) { + tests := []struct { + code string + constraint string + want error + }{ + {code: uniqueViolationCode, constraint: "users_email_normalized_key", want: outbound.ErrEmailTaken}, + {code: uniqueViolationCode, constraint: "email_tokens_token_hash_key", want: outbound.ErrTokenHashConflict}, + {code: uniqueViolationCode, constraint: "sessions_token_hash_key", want: outbound.ErrTokenHashConflict}, + {code: foreignKeyViolationCode, constraint: "email_tokens_user_id_fkey", want: outbound.ErrUserNotFound}, + {code: foreignKeyViolationCode, constraint: "sessions_user_id_fkey", want: outbound.ErrUserNotFound}, + } + for _, test := range tests { + err := mapIdentityError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: "Key (x)=(secret) already exists."}) + if !errors.Is(err, test.want) { + t.Fatalf("mapIdentityError(%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("mapIdentityError(%s) = %v, want the constraint name and no detail", test.constraint, err) + } + } +} + +func TestMapIdentityErrorDropsMessageAndDetailOfOtherPostgreSQLErrors(t *testing.T) { + original := fmt.Errorf("wrapped: %w", &pgconn.PgError{ + Code: "23514", + ConstraintName: "users_password_hash_format", + Message: `new row violates check constraint "users_password_hash_format" for value secret@example.com`, + Detail: "Failing row contains (secret@example.com, $argon2id$v=19$...).", + }) + err := mapIdentityError(original) + var pgError *pgconn.PgError + if errors.As(err, &pgError) { + t.Fatalf("mapIdentityError() kept the PgError: %v", err) + } + var stateError sqlStateError + if !errors.As(err, &stateError) || stateError.SQLState() != "23514" { + t.Fatalf("mapIdentityError() = %v, want SQLSTATE 23514", err) + } + if !strings.Contains(err.Error(), "users_password_hash_format") || + strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "argon2id") { + t.Fatalf("mapIdentityError() = %q, want only the code and constraint", err) + } +} + +func TestMapIdentityErrorKeepsNonPostgreSQLErrors(t *testing.T) { + for _, original := range []error{ + errors.New(`duplicate key value violates unique constraint "users_email_normalized_key"`), + pgx.ErrNoRows, + context.Canceled, + } { + if err := mapIdentityError(original); err != original { //nolint:errorlint // Identity is the property under test. + t.Fatalf("mapIdentityError(%v) = %v, want the original error", original, err) + } + } +} + +func TestMarkTransactionConflictClassifiesDeadlocksAndSerializationFailures(t *testing.T) { + for _, original := range []error{ + &pgconn.PgError{Code: deadlockDetectedCode}, + fmt.Errorf("statement: %w", &pgconn.PgError{Code: serializationFailureCode}), + &databaseError{code: deadlockDetectedCode}, + mapIdentityError(&pgconn.PgError{Code: serializationFailureCode}), + } { + err := markTransactionConflict(original) + if !errors.Is(err, outbound.ErrTransactionConflict) || !errors.Is(err, original) { + t.Fatalf("markTransactionConflict(%v) = %v, want ErrTransactionConflict wrapping the original", original, err) + } + if strings.Count(markTransactionConflict(err).Error(), "markTransactionConflict") != 1 { + t.Fatalf("markTransactionConflict() wrapped an already classified error again: %v", markTransactionConflict(err)) + } + } + for _, original := range []error{ + nil, + &pgconn.PgError{Code: uniqueViolationCode}, + &pgconn.PgError{Code: "55P03"}, + errors.New("connection reset"), + } { + if err := markTransactionConflict(original); err != original { //nolint:errorlint // Identity is the property under test. + t.Fatalf("markTransactionConflict(%v) = %v, want the original error", original, err) + } + } +} + +func TestIdentityStoreRefusesATransactionContext(t *testing.T) { + // A nil pool proves that the guard runs before any statement. + store := &IdentityStore{queries: sqlc.New(standaloneDB{})} + ctx := context.WithValue(t.Context(), transactionContextKey{}, true) + at := time.Now() + checks := map[string]error{ + "GetByID": errorOf(store.Users().GetByID(ctx, uuid.New())), + "DeleteUnverifiedRegisteredBefore": errorOf(store.Users().DeleteUnverifiedRegisteredBefore(ctx, at, 1)), + "Consume": errorOf(store.EmailTokens().Consume(ctx, domain.SecretTokenHash{1}, domain.EmailTokenPurposeEmailVerification, at)), + "InvalidateActive": errorOf(store.EmailTokens().InvalidateActive(ctx, uuid.New(), domain.EmailTokenPurposeEmailVerification, at)), + "Touch": store.Sessions().Touch(ctx, uuid.New(), at, time.Hour), + } + for name, err := range checks { + if !errors.Is(err, outbound.ErrNestedTransaction) { + t.Fatalf("%s() error = %v, want ErrNestedTransaction", name, err) + } + } +} + +// errorOf drops the value of a two-result call. +func errorOf[T any](_ T, err error) error { return err } + +func TestRepositoriesRejectInvalidInputBeforeTheDatabase(t *testing.T) { + // A nil query set proves that validation happens before any statement. + ctx := t.Context() + users, tokens, sessions := userRepository{}, emailTokenRepository{}, sessionRepository{} + now, id, hash := time.Now(), uuid.New(), domain.SecretTokenHash{1} + purpose := domain.EmailTokenPurposeEmailVerification + checks := []struct { + name string + err error + want error + }{ + {name: "Create(zero user)", err: users.Create(ctx, domain.User{}), want: domain.ErrInvalidUser}, + {name: "MarkEmailVerified(zero time)", err: errorOf(users.MarkEmailVerified(ctx, id, 1, time.Time{})), want: domain.ErrInvalidUser}, + {name: "DeleteUnverifiedRegisteredBefore(zero cutoff)", err: errorOf(users.DeleteUnverifiedRegisteredBefore(ctx, time.Time{}, 1)), want: domain.ErrInvalidUser}, + {name: "Insert(zero token)", err: tokens.Insert(ctx, domain.EmailToken{}), want: domain.ErrInvalidEmailToken}, + {name: "Consume(zero time)", err: errorOf(tokens.Consume(ctx, hash, purpose, time.Time{})), want: domain.ErrInvalidEmailToken}, + {name: "InvalidateActive(zero time)", err: errorOf(tokens.InvalidateActive(ctx, id, purpose, time.Time{})), want: domain.ErrInvalidEmailToken}, + {name: "Create(zero session)", err: sessions.Create(ctx, domain.Session{}), want: domain.ErrInvalidSession}, + {name: "FindActive(zero idle timeout)", err: errorOf(sessions.FindActive(ctx, hash, now, 0)), want: domain.ErrInvalidSession}, + {name: "FindActive(zero time)", err: errorOf(sessions.FindActive(ctx, hash, time.Time{}, time.Hour)), want: domain.ErrInvalidSession}, + {name: "Touch(negative idle timeout)", err: sessions.Touch(ctx, id, now, -time.Second), want: domain.ErrInvalidSession}, + {name: "Touch(zero time)", err: sessions.Touch(ctx, id, time.Time{}, time.Hour), want: domain.ErrInvalidSession}, + {name: "Revoke(zero time)", err: sessions.Revoke(ctx, id, time.Time{}), want: domain.ErrInvalidSession}, + {name: "RevokeAllForUser(zero time)", err: errorOf(sessions.RevokeAllForUser(ctx, id, time.Time{})), want: domain.ErrInvalidSession}, + } + for _, check := range checks { + if !errors.Is(check.err, check.want) { + t.Fatalf("%s error = %v, want %v", check.name, check.err, check.want) + } + } + if _, err := users.DeleteUnverifiedRegisteredBefore(ctx, now, 0); err == nil { + t.Fatal("DeleteUnverifiedRegisteredBefore(limit 0) error = nil, want an error") + } +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go new file mode 100644 index 0000000..efe2bd7 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go @@ -0,0 +1,689 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: identity.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const consumeEmailToken = `-- name: ConsumeEmailToken :one +UPDATE email_tokens AS token +SET consumed_at = $1 +FROM users AS owner +WHERE + token.token_hash = $2 + AND token.purpose = $3 + AND token.consumed_at IS NULL + AND token.invalidated_at IS NULL + AND token.expires_at > $1 + AND owner.id = token.user_id + AND owner.registration_version = token.registration_version +RETURNING + token.id, + token.user_id, + token.purpose, + token.token_hash, + token.registration_version, + token.created_at, + token.expires_at, + token.consumed_at, + token.invalidated_at +` + +type ConsumeEmailTokenParams struct { + ConsumedAt pgtype.Timestamptz + TokenHash []byte + Purpose string +} + +// Consumes a token in one statement. Concurrent callers queue on the token +// row lock; under READ COMMITTED each waiter re-checks the WHERE clause +// against the committed row, so exactly one of them updates it. The join +// compares the registration version with the account row as the statement +// reads it, without locking that row, so it rejects a token from an earlier +// registration that already committed but not one that commits afterwards. +// The confirmation guarantee therefore needs MarkUserEmailVerified with the +// returned registration version in the same transaction, rolled back when it +// matches no row. +func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error) { + row := q.db.QueryRow(ctx, consumeEmailToken, arg.ConsumedAt, arg.TokenHash, arg.Purpose) + var i EmailToken + err := row.Scan( + &i.ID, + &i.UserID, + &i.Purpose, + &i.TokenHash, + &i.RegistrationVersion, + &i.CreatedAt, + &i.ExpiresAt, + &i.ConsumedAt, + &i.InvalidatedAt, + ) + return i, err +} + +const deleteUnverifiedUsersRegisteredBefore = `-- name: DeleteUnverifiedUsersRegisteredBefore :execrows +WITH candidate AS ( + SELECT stale.id + FROM users AS stale + WHERE + stale.email_verified_at IS NULL + AND stale.last_registered_at < $1 + ORDER BY stale.last_registered_at + LIMIT $2 + FOR UPDATE SKIP LOCKED +), + +locked_token AS ( + SELECT token.user_id + FROM email_tokens AS token + WHERE token.user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +locked_session AS ( + SELECT session.user_id + FROM sessions AS session + WHERE session.user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +deletable AS ( + SELECT candidate.id + FROM candidate + WHERE + ( + SELECT count(*) FROM email_tokens AS token + WHERE token.user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_token + WHERE locked_token.user_id = candidate.id + ) + AND ( + SELECT count(*) FROM sessions AS session + WHERE session.user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_session + WHERE locked_session.user_id = candidate.id + ) +) + +DELETE FROM users +USING deletable +WHERE users.id = deletable.id +` + +type DeleteUnverifiedUsersRegisteredBeforeParams struct { + Cutoff pgtype.Timestamptz + BatchLimit int32 +} + +// Deletes one batch of accounts that stayed unverified since before cutoff, +// oldest first, with their tokens and sessions. Every lock is taken with SKIP +// LOCKED, so the statement never waits: an account whose row is locked, for +// example by a re-registration or a token insert, is skipped, and so is an +// account with any token or session row locked, for example by a +// confirmation that consumed a token. Skipped accounts stay for the next run. +// Taking the account lock before the token locks is the reverse of the +// documented order, which is safe only because no lock here waits. +// An account qualifies only when every token and session row visible to the +// statement was locked above. +func (q *Queries) DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) { + result, err := q.db.Exec(ctx, deleteUnverifiedUsersRegisteredBefore, arg.Cutoff, arg.BatchLimit) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getActiveSessionByTokenHash = `-- name: GetActiveSessionByTokenHash :one +SELECT + id, + user_id, + token_hash, + created_at, + last_seen_at, + expires_at, + revoked_at +FROM sessions +WHERE + token_hash = $1 + AND revoked_at IS NULL + AND expires_at > $2 + AND last_seen_at > $3 +` + +type GetActiveSessionByTokenHashParams struct { + TokenHash []byte + At pgtype.Timestamptz + IdleCutoff pgtype.Timestamptz +} + +func (q *Queries) GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error) { + row := q.db.QueryRow(ctx, getActiveSessionByTokenHash, arg.TokenHash, arg.At, arg.IdleCutoff) + var i Session + err := row.Scan( + &i.ID, + &i.UserID, + &i.TokenHash, + &i.CreatedAt, + &i.LastSeenAt, + &i.ExpiresAt, + &i.RevokedAt, + ) + return i, err +} + +const getEmailTokenState = `-- name: GetEmailTokenState :one +SELECT + token.consumed_at, + token.invalidated_at, + token.expires_at, + owner.registration_version = token.registration_version AS current_registration +FROM email_tokens AS token +INNER JOIN users AS owner ON token.user_id = owner.id +WHERE + token.token_hash = $1 + AND token.purpose = $2 +` + +type GetEmailTokenStateParams struct { + TokenHash []byte + Purpose string +} + +type GetEmailTokenStateRow struct { + ConsumedAt pgtype.Timestamptz + InvalidatedAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz + CurrentRegistration bool +} + +// Explains why ConsumeEmailToken matched no row. +func (q *Queries) GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) { + row := q.db.QueryRow(ctx, getEmailTokenState, arg.TokenHash, arg.Purpose) + var i GetEmailTokenStateRow + err := row.Scan( + &i.ConsumedAt, + &i.InvalidatedAt, + &i.ExpiresAt, + &i.CurrentRegistration, + ) + return i, err +} + +const getUserByEmailNormalized = `-- name: GetUserByEmailNormalized :one +SELECT + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +FROM users +WHERE email_normalized = $1 +` + +func (q *Queries) GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error) { + row := q.db.QueryRow(ctx, getUserByEmailNormalized, emailNormalized) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.EmailNormalized, + &i.PasswordHash, + &i.Scenario, + &i.OnboardingStep, + &i.EmailVerifiedAt, + &i.RegistrationVersion, + &i.LastRegisteredAt, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const getUserByID = `-- name: GetUserByID :one +SELECT + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +FROM users +WHERE id = $1 +` + +func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) { + row := q.db.QueryRow(ctx, getUserByID, id) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.EmailNormalized, + &i.PasswordHash, + &i.Scenario, + &i.OnboardingStep, + &i.EmailVerifiedAt, + &i.RegistrationVersion, + &i.LastRegisteredAt, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const insertEmailToken = `-- name: InsertEmailToken :exec +INSERT INTO email_tokens ( + id, + user_id, + purpose, + token_hash, + registration_version, + created_at, + expires_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7 +) +` + +type InsertEmailTokenParams struct { + ID pgtype.UUID + UserID pgtype.UUID + Purpose string + TokenHash []byte + RegistrationVersion int64 + CreatedAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz +} + +func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error { + _, err := q.db.Exec(ctx, insertEmailToken, + arg.ID, + arg.UserID, + arg.Purpose, + arg.TokenHash, + arg.RegistrationVersion, + arg.CreatedAt, + arg.ExpiresAt, + ) + return err +} + +const insertSession = `-- name: InsertSession :exec +INSERT INTO sessions ( + id, + user_id, + token_hash, + created_at, + last_seen_at, + expires_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6 +) +` + +type InsertSessionParams struct { + ID pgtype.UUID + UserID pgtype.UUID + TokenHash []byte + CreatedAt pgtype.Timestamptz + LastSeenAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz +} + +func (q *Queries) InsertSession(ctx context.Context, arg InsertSessionParams) error { + _, err := q.db.Exec(ctx, insertSession, + arg.ID, + arg.UserID, + arg.TokenHash, + arg.CreatedAt, + arg.LastSeenAt, + arg.ExpiresAt, + ) + return err +} + +const insertUser = `-- name: InsertUser :exec +INSERT INTO users ( + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8, + $9, + $10, + $11, + $12 +) +` + +type InsertUserParams struct { + ID pgtype.UUID + Email string + EmailNormalized string + PasswordHash string + Scenario string + OnboardingStep string + EmailVerifiedAt pgtype.Timestamptz + RegistrationVersion int64 + LastRegisteredAt pgtype.Timestamptz + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + +func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) error { + _, err := q.db.Exec(ctx, insertUser, + arg.ID, + arg.Email, + arg.EmailNormalized, + arg.PasswordHash, + arg.Scenario, + arg.OnboardingStep, + arg.EmailVerifiedAt, + arg.RegistrationVersion, + arg.LastRegisteredAt, + arg.Version, + arg.CreatedAt, + arg.UpdatedAt, + ) + return err +} + +const invalidateActiveEmailTokens = `-- name: InvalidateActiveEmailTokens :execrows +UPDATE email_tokens +SET invalidated_at = $1 +WHERE + user_id = $2 + AND purpose = $3 + AND consumed_at IS NULL + AND invalidated_at IS NULL +` + +type InvalidateActiveEmailTokensParams struct { + InvalidatedAt pgtype.Timestamptz + UserID pgtype.UUID + Purpose string +} + +func (q *Queries) InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error) { + result, err := q.db.Exec(ctx, invalidateActiveEmailTokens, arg.InvalidatedAt, arg.UserID, arg.Purpose) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const markUserEmailVerified = `-- name: MarkUserEmailVerified :one +UPDATE users +SET + email_verified_at = $1, + updated_at = $1, + version = version + 1 +WHERE + id = $2 + AND registration_version = $3 + AND email_verified_at IS NULL +RETURNING + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +` + +type MarkUserEmailVerifiedParams struct { + VerifiedAt pgtype.Timestamptz + ID pgtype.UUID + RegistrationVersion int64 +} + +// Verifies the email only for the registration version the consumed token +// was issued for. +func (q *Queries) MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error) { + row := q.db.QueryRow(ctx, markUserEmailVerified, arg.VerifiedAt, arg.ID, arg.RegistrationVersion) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.EmailNormalized, + &i.PasswordHash, + &i.Scenario, + &i.OnboardingStep, + &i.EmailVerifiedAt, + &i.RegistrationVersion, + &i.LastRegisteredAt, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const revokeSession = `-- name: RevokeSession :execrows +UPDATE sessions +SET revoked_at = $1 +WHERE + id = $2 + AND revoked_at IS NULL +` + +type RevokeSessionParams struct { + RevokedAt pgtype.Timestamptz + ID pgtype.UUID +} + +func (q *Queries) RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error) { + result, err := q.db.Exec(ctx, revokeSession, arg.RevokedAt, arg.ID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const revokeUserSessions = `-- name: RevokeUserSessions :execrows +UPDATE sessions +SET revoked_at = $1 +WHERE + user_id = $2 + AND revoked_at IS NULL +` + +type RevokeUserSessionsParams struct { + RevokedAt pgtype.Timestamptz + UserID pgtype.UUID +} + +func (q *Queries) RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error) { + result, err := q.db.Exec(ctx, revokeUserSessions, arg.RevokedAt, arg.UserID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const touchSession = `-- name: TouchSession :one +WITH active_session AS ( + SELECT candidate.id + FROM sessions AS candidate + WHERE + candidate.id = $1 + AND candidate.revoked_at IS NULL + AND candidate.expires_at > $2 + AND candidate.last_seen_at > $3 +), + +touched AS ( + UPDATE sessions + SET last_seen_at = $2 + WHERE + sessions.id = $1 + AND sessions.revoked_at IS NULL + AND sessions.expires_at > $2 + AND sessions.last_seen_at > $3 + AND sessions.last_seen_at < $4 + RETURNING sessions.id +) + +SELECT + exists(SELECT 1 FROM active_session) AS active, + exists(SELECT 1 FROM touched) AS touched +` + +type TouchSessionParams struct { + ID pgtype.UUID + At pgtype.Timestamptz + IdleCutoff pgtype.Timestamptz + TouchCutoff pgtype.Timestamptz +} + +type TouchSessionRow struct { + Active bool + Touched bool +} + +// Records activity on an active session and reports whether it is active. +// The row is written only when last_seen_at is older than touch_cutoff, so +// frequent requests do not rewrite it. last_seen_at never moves back, and a +// revoked, expired, or idle session is not revived; the update re-checks +// those conditions against a concurrent change. +func (q *Queries) TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error) { + row := q.db.QueryRow(ctx, touchSession, + arg.ID, + arg.At, + arg.IdleCutoff, + arg.TouchCutoff, + ) + var i TouchSessionRow + err := row.Scan(&i.Active, &i.Touched) + return i, err +} + +const updateUserRegistration = `-- name: UpdateUserRegistration :one +UPDATE users +SET + email = $1, + password_hash = $2, + scenario = $3, + onboarding_step = $4, + registration_version = registration_version + 1, + last_registered_at = $5, + updated_at = $6, + version = version + 1 +WHERE + id = $7 + AND version = $8 + AND email_verified_at IS NULL +RETURNING + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +` + +type UpdateUserRegistrationParams struct { + Email string + PasswordHash string + Scenario string + OnboardingStep string + LastRegisteredAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + ID pgtype.UUID + ExpectedVersion int64 +} + +// Replaces the registration of an unverified account and advances the +// registration version in the same statement, so no caller can choose it. +// The version check rejects a writer that read an older row; a verified +// account never changes. +func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error) { + row := q.db.QueryRow(ctx, updateUserRegistration, + arg.Email, + arg.PasswordHash, + arg.Scenario, + arg.OnboardingStep, + arg.LastRegisteredAt, + arg.UpdatedAt, + arg.ID, + arg.ExpectedVersion, + ) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.EmailNormalized, + &i.PasswordHash, + &i.Scenario, + &i.OnboardingStep, + &i.EmailVerifiedAt, + &i.RegistrationVersion, + &i.LastRegisteredAt, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 8c2fcaf..8c5461c 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -8,6 +8,18 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +type EmailToken struct { + ID pgtype.UUID + UserID pgtype.UUID + Purpose string + TokenHash []byte + RegistrationVersion int64 + CreatedAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz + ConsumedAt pgtype.Timestamptz + InvalidatedAt pgtype.Timestamptz +} + type OutboxEvent struct { Position pgtype.Int8 EventID pgtype.UUID @@ -20,3 +32,28 @@ type OutboxEvent struct { OccurredAt pgtype.Timestamptz PublishedAt pgtype.Timestamptz } + +type Session struct { + ID pgtype.UUID + UserID pgtype.UUID + TokenHash []byte + CreatedAt pgtype.Timestamptz + LastSeenAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz +} + +type User struct { + ID pgtype.UUID + Email string + EmailNormalized string + PasswordHash string + Scenario string + OnboardingStep string + EmailVerifiedAt pgtype.Timestamptz + RegistrationVersion int64 + LastRegisteredAt pgtype.Timestamptz + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index c508693..eef61c1 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -6,11 +6,59 @@ package sqlc import ( "context" + + "github.com/jackc/pgx/v5/pgtype" ) type Querier interface { + // Consumes a token in one statement. Concurrent callers queue on the token + // row lock; under READ COMMITTED each waiter re-checks the WHERE clause + // against the committed row, so exactly one of them updates it. The join + // compares the registration version with the account row as the statement + // reads it, without locking that row, so it rejects a token from an earlier + // registration that already committed but not one that commits afterwards. + // The confirmation guarantee therefore needs MarkUserEmailVerified with the + // returned registration version in the same transaction, rolled back when it + // matches no row. + ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error) + // Deletes one batch of accounts that stayed unverified since before cutoff, + // oldest first, with their tokens and sessions. Every lock is taken with SKIP + // LOCKED, so the statement never waits: an account whose row is locked, for + // example by a re-registration or a token insert, is skipped, and so is an + // account with any token or session row locked, for example by a + // confirmation that consumed a token. Skipped accounts stay for the next run. + // Taking the account lock before the token locks is the reverse of the + // documented order, which is safe only because no lock here waits. + // An account qualifies only when every token and session row visible to the + // statement was locked above. + DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) + GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error) + // Explains why ConsumeEmailToken matched no row. + GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, 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 + InsertSession(ctx context.Context, arg InsertSessionParams) error + InsertUser(ctx context.Context, arg InsertUserParams) error + InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error) + // Verifies the email only for the registration version the consumed token + // was issued for. + MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error) Ping(ctx context.Context) (int32, 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. + // The row is written only when last_seen_at is older than touch_cutoff, so + // frequent requests do not rewrite it. last_seen_at never moves back, and a + // revoked, expired, or idle session is not revived; the update re-checks + // those conditions against a concurrent change. + TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error) + // Replaces the registration of an unverified account and advances the + // registration version in the same statement, so no caller can choose it. + // The version check rejects a writer that read an older row; a verified + // account never changes. + UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error) } var _ Querier = (*Queries)(nil) diff --git a/backend/internal/adapter/secondary/postgres/transactor.go b/backend/internal/adapter/secondary/postgres/transactor.go index 6d215ff..942fb29 100644 --- a/backend/internal/adapter/secondary/postgres/transactor.go +++ b/backend/internal/adapter/secondary/postgres/transactor.go @@ -66,6 +66,7 @@ func (transactor *Transactor) WithinTransaction( fnErr := fn(context.WithValue(ctx, transactionContextKey{}, true), &UnitOfWork{tx: tx, queries: sqlc.New(tx)}) finished = true if fnErr != nil { + fnErr = markTransactionConflict(fnErr) if rollbackErr := rollback(ctx, tx); rollbackErr != nil { return errors.Join(fnErr, fmt.Errorf("Transactor.WithinTransaction - roll back transaction: %w", rollbackErr)) } @@ -75,7 +76,7 @@ func (transactor *Transactor) WithinTransaction( // pgx reports pgx.ErrTxCommitRollback when fn ignored a statement error // and PostgreSQL rolled the aborted transaction back instead. After a // network error the commit outcome is unknown; see outbound.Transactor. - return fmt.Errorf("Transactor.WithinTransaction - commit transaction: %w", err) + return fmt.Errorf("Transactor.WithinTransaction - commit transaction: %w", markTransactionConflict(err)) } return nil } diff --git a/backend/internal/domain/email_address.go b/backend/internal/domain/email_address.go new file mode 100644 index 0000000..1bc5274 --- /dev/null +++ b/backend/internal/domain/email_address.go @@ -0,0 +1,157 @@ +package domain + +import ( + "errors" + "fmt" + "log/slog" + "strings" +) + +const ( + // Bounds follow the EmailAddress schema in the public contract (3 to 254 + // characters) and the RFC 5321 local-part limit of 64 octets. Addresses + // are ASCII, so characters and bytes coincide. + minEmailAddressLength = 3 + maxEmailAddressLength = 254 + maxEmailLocalPartSize = 64 + maxEmailDomainLabel = 63 + redactedEmailAddress = "[redacted email]" + asciiWhitespace = " \t\n\v\f\r" +) + +var ErrInvalidEmailAddress = errors.New("invalid email address") + +// EmailAddress is a syntactically valid ASCII account email in two forms. +// +// Address is the delivery form: the input with surrounding ASCII whitespace +// removed, in the letter case the user typed, because RFC 5321 allows a +// case-sensitive local part. The account view returns it. +// +// Normalized is the comparison key: the address with A-Z lowercased. Storage +// keeps it unique, so addresses that differ only in letter case conflict. Go +// owns this rule; the database never recomputes the key, because PostgreSQL +// lower() depends on the collation. +// +// Only ASCII addresses are accepted because the mailer does not support +// SMTPUTF8. Internationalized domains are accepted in their ASCII (punycode) +// form. Accepting Unicode addresses is future work: it needs IDNA ToASCII for +// the domain, a rule for Unicode local parts, and SMTPUTF8 delivery. +// +// String, GoString, Format, and LogValue redact the address so it does not +// reach logs by accident; Address returns the real value. +type EmailAddress struct { + address string + normalized string +} + +// NewEmailAddress validates raw and returns both forms. It rejects non-ASCII +// characters, display names, quoted local parts, comments, whitespace or +// control characters inside the address, IP-literal domains, and domains +// without a dot. The outcome depends only on raw, never on stored accounts. +func NewEmailAddress(raw string) (EmailAddress, error) { + // Only ASCII whitespace is trimmed; any other character is validated. + address := strings.Trim(raw, asciiWhitespace) + for index := range len(address) { + if address[index] <= ' ' || address[index] > '~' { + return EmailAddress{}, invalidEmailAddress("address must contain printable ASCII characters only") + } + } + if length := len(address); length < minEmailAddressLength || length > maxEmailAddressLength { + return EmailAddress{}, invalidEmailAddress("address must have 3 to 254 characters") + } + localPart, domainPart, found := strings.Cut(address, "@") + if !found || strings.Contains(domainPart, "@") { + return EmailAddress{}, invalidEmailAddress("address must contain exactly one @") + } + if err := validateEmailLocalPart(localPart); err != nil { + return EmailAddress{}, err + } + if err := validateEmailDomain(domainPart); err != nil { + return EmailAddress{}, err + } + return EmailAddress{address: address, normalized: normalizeEmailKey(address)}, nil +} + +// RestoreEmailAddress rebuilds an EmailAddress from storage. It checks only +// that the stored key matches the stored address, so a later, stricter +// NewEmailAddress rule does not make existing accounts unreadable. +func RestoreEmailAddress(address, normalized string) (EmailAddress, error) { + if address == "" || normalized != normalizeEmailKey(address) { + return EmailAddress{}, fmt.Errorf("domain.RestoreEmailAddress - stored key does not match the stored address: %w", ErrInvalidEmailAddress) + } + return EmailAddress{address: address, normalized: normalized}, nil +} + +// normalizeEmailKey lowercases A-Z only, independent of locale and Unicode +// case rules. +func normalizeEmailKey(address string) string { + return strings.Map(func(character rune) rune { + if 'A' <= character && character <= 'Z' { + return character + ('a' - 'A') + } + return character + }, address) +} + +func validateEmailLocalPart(localPart string) error { + if localPart == "" || len(localPart) > maxEmailLocalPartSize { + return invalidEmailAddress("local part must have 1 to 64 characters") + } + if strings.HasPrefix(localPart, ".") || strings.HasSuffix(localPart, ".") || strings.Contains(localPart, "..") { + return invalidEmailAddress("local part must not start or end with a dot or contain consecutive dots") + } + for _, character := range localPart { + if !isASCIILetterOrDigit(character) && !strings.ContainsRune(".!#$%&'*+-/=?^_`{|}~", character) { + return invalidEmailAddress("local part contains a character outside an unquoted dot-atom") + } + } + return nil +} + +func validateEmailDomain(domainPart string) error { + labels := strings.Split(domainPart, ".") + if len(labels) < 2 { + return invalidEmailAddress("domain must contain at least two labels") + } + for _, label := range labels { + if label == "" || len(label) > maxEmailDomainLabel { + return invalidEmailAddress("domain labels must have 1 to 63 characters") + } + if strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") { + return invalidEmailAddress("domain labels must not start or end with a hyphen") + } + for _, character := range label { + if !isASCIILetterOrDigit(character) && character != '-' { + return invalidEmailAddress("domain contains a character outside letters, digits, and hyphens") + } + } + } + return nil +} + +func isASCIILetterOrDigit(character rune) bool { + return ('a' <= character && character <= 'z') || ('A' <= character && character <= 'Z') || ('0' <= character && character <= '9') +} + +func invalidEmailAddress(reason string) error { + return fmt.Errorf("domain.NewEmailAddress - %s: %w", reason, ErrInvalidEmailAddress) +} + +// Address returns the delivery form. Use it only where the address is needed: +// storage, mail delivery, and the account view. +func (email EmailAddress) Address() string { return email.address } + +// Normalized returns the comparison key that storage keeps unique. +func (email EmailAddress) Normalized() string { return email.normalized } + +// IsZero reports an EmailAddress not built by NewEmailAddress. +func (email EmailAddress) IsZero() bool { return email.normalized == "" } + +func (email EmailAddress) String() string { return redactedEmailAddress } + +func (email EmailAddress) GoString() string { return redactedEmailAddress } + +// Format redacts every verb; without it %d would print the struct fields. +func (email EmailAddress) Format(state fmt.State, _ rune) { writeRedacted(state, redactedEmailAddress) } + +func (email EmailAddress) LogValue() slog.Value { return slog.StringValue(redactedEmailAddress) } diff --git a/backend/internal/domain/email_address_test.go b/backend/internal/domain/email_address_test.go new file mode 100644 index 0000000..82811bf --- /dev/null +++ b/backend/internal/domain/email_address_test.go @@ -0,0 +1,145 @@ +package domain + +import ( + "bytes" + "errors" + "fmt" + "log/slog" + "strings" + "testing" +) + +func TestNewEmailAddressNormalizes(t *testing.T) { + tests := []struct { + name string + raw string + wantAddress string + wantNormalized string + }{ + {name: "plain", raw: "candidate@example.com", wantAddress: "candidate@example.com", wantNormalized: "candidate@example.com"}, + {name: "trims and keeps case for delivery", raw: " \tAlice.Smith@Example.COM\n", wantAddress: "Alice.Smith@Example.COM", wantNormalized: "alice.smith@example.com"}, + {name: "atext characters", raw: "O'Neil+Tag_1!#$%&*/=?^`{|}~-x@example.com", wantAddress: "O'Neil+Tag_1!#$%&*/=?^`{|}~-x@example.com", wantNormalized: "o'neil+tag_1!#$%&*/=?^`{|}~-x@example.com"}, + {name: "punycode domain stays ASCII", raw: "Info@XN--E1AFMKFD.xn--p1ai", wantAddress: "Info@XN--E1AFMKFD.xn--p1ai", wantNormalized: "info@xn--e1afmkfd.xn--p1ai"}, + {name: "minimum length", raw: "a@b.c", wantAddress: "a@b.c", wantNormalized: "a@b.c"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + email, err := NewEmailAddress(test.raw) + if err != nil { + t.Fatalf("NewEmailAddress(%q) error = %v", test.raw, err) + } + if email.Address() != test.wantAddress || email.Normalized() != test.wantNormalized { + t.Fatalf("NewEmailAddress(%q) = (%q, %q), want (%q, %q)", + test.raw, email.Address(), email.Normalized(), test.wantAddress, test.wantNormalized) + } + }) + } +} + +func TestNewEmailAddressCaseVariantsShareTheKey(t *testing.T) { + variants := []string{"Candidate@Example.com", "CANDIDATE@EXAMPLE.COM", " candidate@example.com "} + first, err := NewEmailAddress(variants[0]) + if err != nil { + t.Fatalf("NewEmailAddress(%q) error = %v", variants[0], err) + } + for _, variant := range variants[1:] { + email, err := NewEmailAddress(variant) + if err != nil { + t.Fatalf("NewEmailAddress(%q) error = %v", variant, err) + } + if email.Normalized() != first.Normalized() { + t.Fatalf("Normalized(%q) = %q, want %q", variant, email.Normalized(), first.Normalized()) + } + } +} + +func TestNewEmailAddressRejectsInvalidInput(t *testing.T) { + longLocal := strings.Repeat("a", maxEmailLocalPartSize+1) + "@example.com" + longLabel := "a@" + strings.Repeat("b", maxEmailDomainLabel+1) + ".com" + tooLong := strings.Repeat("a", 60) + "@" + strings.Repeat(strings.Repeat("b", 60)+".", 3) + "example.com" + tests := map[string]string{ + "empty": "", + "blank": " ", + "too short": "a@", + "too long": tooLong, + "no at": "candidate.example.com", + "two ats": "a@b@example.com", + "empty local part": "@example.com", + "empty domain": "candidate@", + "single-label domain": "candidate@localhost", + "leading dot": ".candidate@example.com", + "trailing dot": "candidate.@example.com", + "consecutive dots": "can..didate@example.com", + "inner space": "can didate@example.com", + "quoted local part": `"can didate"@example.com`, + "display name": "Candidate ", + "comment": "candidate(comment)@example.com", + "control character": "cand\x00idate@example.com", + "empty domain label": "candidate@example..com", + "hyphen edge label": "candidate@-example.com", + "ip literal": "candidate@[127.0.0.1]", + "underscore in domain": "candidate@exa_mple.com", + "local part too long": longLocal, + "domain label too long": longLabel, + "invalid utf-8": "cand\xffidate@example.com", + // Non-ASCII input is rejected until IDNA and SMTPUTF8 are supported. + "dotted capital I": "İnfo@x.com", + "fullwidth domain": "info@example.com", + "mixed-script homoglyph": "pаypal@example.com", + "cyrillic domain": "info@пример.рф", + "decomposed accent": "José@example.com", + "non-breaking space trim": " candidate@example.com", + } + for name, raw := range tests { + t.Run(name, func(t *testing.T) { + if _, err := NewEmailAddress(raw); !errors.Is(err, ErrInvalidEmailAddress) { + t.Fatalf("NewEmailAddress(%q) error = %v, want ErrInvalidEmailAddress", raw, err) + } + }) + } +} + +func TestRestoreEmailAddressChecksOnlyConsistency(t *testing.T) { + // A stored address that today's rule would reject still restores, as long + // as its key matches. + restored, err := RestoreEmailAddress("Legacy@Host", "legacy@host") + if err != nil { + t.Fatalf("RestoreEmailAddress(consistent) error = %v", err) + } + if restored.Address() != "Legacy@Host" || restored.Normalized() != "legacy@host" { + t.Fatalf("RestoreEmailAddress() = (%q, %q)", restored.Address(), restored.Normalized()) + } + for _, pair := range [][2]string{{"Legacy@Host", "Legacy@Host"}, {"a@example.com", "b@example.com"}, {"", ""}} { + if _, err := RestoreEmailAddress(pair[0], pair[1]); !errors.Is(err, ErrInvalidEmailAddress) { + t.Fatalf("RestoreEmailAddress(%q, %q) error = %v, want ErrInvalidEmailAddress", pair[0], pair[1], err) + } + } +} + +func TestEmailAddressZeroValue(t *testing.T) { + if !(EmailAddress{}).IsZero() { + t.Fatal("zero EmailAddress is not reported as zero") + } + email, err := NewEmailAddress("candidate@example.com") + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + if email.IsZero() { + t.Fatal("valid EmailAddress is reported as zero") + } +} + +func TestEmailAddressIsRedacted(t *testing.T) { + email, err := NewEmailAddress("Secret.Person@Example.com") + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + var logs bytes.Buffer + slog.New(slog.NewJSONHandler(&logs, nil)).Info("redaction", "email", email) + formatted := fmt.Sprintf("%v %+v %#v %s %q %x %d", email, email, email, email, email, email, email) + logs.String() + for _, secret := range []string{email.Address(), email.Normalized(), "Secret", "secret"} { + if strings.Contains(formatted, secret) { + t.Fatalf("formatted output exposes the address: %s", formatted) + } + } +} diff --git a/backend/internal/domain/email_token.go b/backend/internal/domain/email_token.go new file mode 100644 index 0000000..c29924c --- /dev/null +++ b/backend/internal/domain/email_token.go @@ -0,0 +1,90 @@ +package domain + +import ( + "errors" + "fmt" + "time" + + "github.com/google/uuid" +) + +var ErrInvalidEmailToken = errors.New("invalid email token") + +// EmailTokenPurpose names what an email token authorizes. New purposes, such +// as a planned password reset, are added here and in the email_tokens CHECK +// constraint together. +type EmailTokenPurpose string + +// EmailTokenPurposeEmailVerification authorizes confirming the account email. +const EmailTokenPurposeEmailVerification EmailTokenPurpose = "email_verification" //nolint:gosec // A purpose name, not a credential. + +// ParseEmailTokenPurpose accepts a known purpose. +func ParseEmailTokenPurpose(value string) (EmailTokenPurpose, error) { + purpose := EmailTokenPurpose(value) + if purpose != EmailTokenPurposeEmailVerification { + return "", fmt.Errorf("domain.ParseEmailTokenPurpose - unknown purpose: %w", ErrInvalidEmailToken) + } + return purpose, nil +} + +// EmailToken is the stored record of a one-time token sent by email. It holds +// only the hash of the raw token. A token ends at most once: it is either +// consumed or invalidated, and it stops working at ExpiresAt. +type EmailToken struct { + ID uuid.UUID + UserID uuid.UUID + Purpose EmailTokenPurpose + TokenHash SecretTokenHash + RegistrationVersion int64 + CreatedAt time.Time + ExpiresAt time.Time + ConsumedAt *time.Time + InvalidatedAt *time.Time +} + +// NewEmailTokenInput describes a token to issue. RegistrationVersion is the +// user's current registration version. +type NewEmailTokenInput struct { + UserID uuid.UUID + Purpose EmailTokenPurpose + TokenHash SecretTokenHash + RegistrationVersion int64 + IssuedAt time.Time + Lifetime time.Duration +} + +// NewEmailToken validates input and assigns a UUIDv7 identifier. +func NewEmailToken(input NewEmailTokenInput) (EmailToken, error) { + switch { + case input.UserID == uuid.Nil: + return EmailToken{}, invalidEmailToken("user ID must not be nil") + case input.TokenHash.IsZero(): + return EmailToken{}, invalidEmailToken("token hash must be set") + case input.RegistrationVersion <= 0: + return EmailToken{}, invalidEmailToken("registration version must be positive") + case input.IssuedAt.IsZero(): + return EmailToken{}, invalidEmailToken("issue time must be set") + case input.Lifetime <= 0: + return EmailToken{}, invalidEmailToken("lifetime must be positive") + } + if _, err := ParseEmailTokenPurpose(string(input.Purpose)); err != nil { + return EmailToken{}, fmt.Errorf("domain.NewEmailToken - validate purpose: %w", err) + } + id, err := uuid.NewV7() + if err != nil { + return EmailToken{}, fmt.Errorf("domain.NewEmailToken - generate token ID: %w", err) + } + return EmailToken{ + ID: id, + UserID: input.UserID, + Purpose: input.Purpose, + TokenHash: input.TokenHash, + RegistrationVersion: input.RegistrationVersion, + CreatedAt: input.IssuedAt, + ExpiresAt: input.IssuedAt.Add(input.Lifetime), + }, nil +} + +func invalidEmailToken(reason string) error { + return fmt.Errorf("domain.NewEmailToken - %s: %w", reason, ErrInvalidEmailToken) +} diff --git a/backend/internal/domain/email_token_test.go b/backend/internal/domain/email_token_test.go new file mode 100644 index 0000000..5750668 --- /dev/null +++ b/backend/internal/domain/email_token_test.go @@ -0,0 +1,66 @@ +package domain + +import ( + "errors" + "testing" + "time" + + "github.com/google/uuid" +) + +func testTokenHash(t *testing.T) SecretTokenHash { + t.Helper() + token, err := NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + return token.Hash() +} + +func TestNewEmailTokenSetsExpiryFromLifetime(t *testing.T) { + input := NewEmailTokenInput{ + UserID: uuid.New(), + Purpose: EmailTokenPurposeEmailVerification, + TokenHash: testTokenHash(t), + RegistrationVersion: 3, + IssuedAt: testRegisteredAt, + Lifetime: 24 * time.Hour, + } + token, err := NewEmailToken(input) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + if token.ID.Version() != 7 || token.UserID != input.UserID || token.TokenHash != input.TokenHash || + token.RegistrationVersion != 3 || !token.CreatedAt.Equal(testRegisteredAt) || + !token.ExpiresAt.Equal(testRegisteredAt.Add(24*time.Hour)) || token.ConsumedAt != nil || token.InvalidatedAt != nil { + t.Fatalf("NewEmailToken() = %+v", token) + } +} + +func TestNewEmailTokenRejectsInvalidInput(t *testing.T) { + valid := NewEmailTokenInput{ + UserID: uuid.New(), + Purpose: EmailTokenPurposeEmailVerification, + TokenHash: testTokenHash(t), + RegistrationVersion: 1, + IssuedAt: testRegisteredAt, + Lifetime: time.Hour, + } + tests := map[string]func(*NewEmailTokenInput){ + "nil user": func(input *NewEmailTokenInput) { input.UserID = uuid.Nil }, + "unknown purpose": func(input *NewEmailTokenInput) { input.Purpose = "password_reset" }, + "zero hash": func(input *NewEmailTokenInput) { input.TokenHash = SecretTokenHash{} }, + "zero version": func(input *NewEmailTokenInput) { input.RegistrationVersion = 0 }, + "zero issue time": func(input *NewEmailTokenInput) { input.IssuedAt = time.Time{} }, + "non-positive lifetime": func(input *NewEmailTokenInput) { input.Lifetime = 0 }, + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + input := valid + mutate(&input) + if _, err := NewEmailToken(input); !errors.Is(err, ErrInvalidEmailToken) { + t.Fatalf("NewEmailToken() error = %v, want ErrInvalidEmailToken", err) + } + }) + } +} diff --git a/backend/internal/domain/secret_token.go b/backend/internal/domain/secret_token.go new file mode 100644 index 0000000..56d498a --- /dev/null +++ b/backend/internal/domain/secret_token.go @@ -0,0 +1,88 @@ +package domain + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "errors" + "fmt" + "log/slog" + "regexp" +) + +const ( + // secretTokenEntropyBytes gives 256 bits of entropy. The encoded value is + // 43 base64url characters, inside the 32 to 128 character bounds that the + // contract sets for VerificationToken and CsrfToken. + secretTokenEntropyBytes = 32 + // SecretTokenHashSize is the size of a SHA-256 digest. + SecretTokenHashSize = sha256.Size + redactedSecret = "[redacted]" +) + +var ( + ErrInvalidSecretToken = errors.New("invalid secret token") + + // The contract pattern for raw tokens that arrive in requests. + secretTokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{32,128}$`) +) + +// SecretToken is a random bearer secret: the token in an email link or the +// session cookie value. Only the holder sees the raw value; storage keeps +// SecretTokenHash. String and LogValue redact the value so it does not reach +// logs by accident; Reveal returns it for the one place that must send it. +type SecretToken struct { + value string +} + +// NewSecretToken returns a token with 256 bits from crypto/rand. +func NewSecretToken() (SecretToken, error) { + entropy := make([]byte, secretTokenEntropyBytes) + if _, err := rand.Read(entropy); err != nil { + return SecretToken{}, fmt.Errorf("domain.NewSecretToken - read random bytes: %w", err) + } + return SecretToken{value: base64.RawURLEncoding.EncodeToString(entropy)}, nil +} + +// ParseSecretToken accepts a raw token from a request. It checks only the +// contract shape; whether the token exists is decided by its hash in storage. +func ParseSecretToken(raw string) (SecretToken, error) { + if !secretTokenPattern.MatchString(raw) { + return SecretToken{}, fmt.Errorf("domain.ParseSecretToken - token must have 32 to 128 base64url characters: %w", ErrInvalidSecretToken) + } + return SecretToken{value: raw}, nil +} + +// Hash returns the SHA-256 digest that storage keeps. A token carries 256 bits +// of entropy, so a fast unsalted digest cannot be reversed by guessing, unlike +// a password, and lookups by digest stay a single index probe. +func (token SecretToken) Hash() SecretTokenHash { + return SecretTokenHash(sha256.Sum256([]byte(token.value))) +} + +// Reveal returns the raw value for delivery to its holder: the email link or +// the Set-Cookie header. Never store or log it. +func (token SecretToken) Reveal() string { return token.value } + +func (token SecretToken) String() string { return redactedSecret } + +func (token SecretToken) GoString() string { return redactedSecret } + +func (token SecretToken) LogValue() slog.Value { return slog.StringValue(redactedSecret) } + +// Format redacts every verb; without it %d would print the struct fields. +func (token SecretToken) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } + +func writeRedacted(state fmt.State, placeholder string) { + _, _ = state.Write([]byte(placeholder)) +} + +// IsZero reports a SecretToken not built by NewSecretToken or ParseSecretToken. +func (token SecretToken) IsZero() bool { return token.value == "" } + +// SecretTokenHash is the SHA-256 digest of a SecretToken. +type SecretTokenHash [SecretTokenHashSize]byte + +// IsZero reports the all-zero value, which no real token hashes to in practice +// and which marks a missing hash. +func (hash SecretTokenHash) IsZero() bool { return hash == SecretTokenHash{} } diff --git a/backend/internal/domain/secret_token_test.go b/backend/internal/domain/secret_token_test.go new file mode 100644 index 0000000..9121cc8 --- /dev/null +++ b/backend/internal/domain/secret_token_test.go @@ -0,0 +1,80 @@ +package domain + +import ( + "bytes" + "crypto/sha256" + "errors" + "fmt" + "log/slog" + "strings" + "testing" +) + +func TestNewSecretTokenMatchesTheContractShape(t *testing.T) { + token, err := NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + parsed, err := ParseSecretToken(token.Reveal()) + if err != nil { + t.Fatalf("ParseSecretToken(generated) error = %v", err) + } + if parsed.Hash() != token.Hash() { + t.Fatal("a parsed token hashes differently from the generated one") + } + other, err := NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + if other.Reveal() == token.Reveal() { + t.Fatal("NewSecretToken() repeated a value") + } +} + +func TestSecretTokenHashIsSHA256OfTheRawValue(t *testing.T) { + raw := strings.Repeat("A", 43) + token, err := ParseSecretToken(raw) + if err != nil { + t.Fatalf("ParseSecretToken() error = %v", err) + } + if want := sha256.Sum256([]byte(raw)); token.Hash() != SecretTokenHash(want) { + t.Fatal("Hash() is not the SHA-256 digest of the raw token") + } + if token.Hash().IsZero() || !(SecretTokenHash{}).IsZero() { + t.Fatal("IsZero() does not distinguish a real digest from the zero value") + } +} + +func TestParseSecretTokenRejectsValuesOutsideTheContract(t *testing.T) { + for _, raw := range []string{ + "", + strings.Repeat("a", 31), + strings.Repeat("a", 129), + strings.Repeat("a", 40) + "=", + strings.Repeat("a", 40) + "+/", + strings.Repeat("a", 40) + " ", + } { + if _, err := ParseSecretToken(raw); !errors.Is(err, ErrInvalidSecretToken) { + t.Fatalf("ParseSecretToken(%q) error = %v, want ErrInvalidSecretToken", raw, err) + } + } +} + +func TestSecretTokenAndPasswordHashAreRedacted(t *testing.T) { + token, err := NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + passwordHash, err := NewPasswordHash(testPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + var logs bytes.Buffer + slog.New(slog.NewTextHandler(&logs, nil)).Info("redaction", "token", token, "hash", passwordHash) + formatted := fmt.Sprintf("%v %+v %#v %s %v %#v", token, token, token, passwordHash, passwordHash, passwordHash) + logs.String() + for _, secret := range []string{token.Reveal(), testPasswordHash} { + if strings.Contains(formatted, secret) { + t.Fatalf("formatted output exposes a secret: %s", formatted) + } + } +} diff --git a/backend/internal/domain/session.go b/backend/internal/domain/session.go new file mode 100644 index 0000000..81a517a --- /dev/null +++ b/backend/internal/domain/session.go @@ -0,0 +1,67 @@ +package domain + +import ( + "errors" + "fmt" + "time" + + "github.com/google/uuid" +) + +var ErrInvalidSession = errors.New("invalid session") + +// Session is a server-side login session. The cookie carries the raw +// SecretToken; storage keeps only TokenHash. ID identifies the session inside +// the server, for example to revoke it, and never leaves the server. +// +// A session is active while it is not revoked, ExpiresAt (the absolute +// deadline) is in the future, and LastSeenAt is within the idle timeout. +// Activity moves only LastSeenAt. +type Session struct { + ID uuid.UUID + UserID uuid.UUID + TokenHash SecretTokenHash + CreatedAt time.Time + LastSeenAt time.Time + ExpiresAt time.Time + RevokedAt *time.Time +} + +// NewSessionInput describes a session to start. AbsoluteLifetime fixes +// ExpiresAt; the idle timeout is applied when the session is looked up. +type NewSessionInput struct { + UserID uuid.UUID + TokenHash SecretTokenHash + StartedAt time.Time + AbsoluteLifetime time.Duration +} + +// NewSession validates input and assigns a UUIDv7 identifier. +func NewSession(input NewSessionInput) (Session, error) { + switch { + case input.UserID == uuid.Nil: + return Session{}, invalidSession("user ID must not be nil") + case input.TokenHash.IsZero(): + return Session{}, invalidSession("token hash must be set") + case input.StartedAt.IsZero(): + return Session{}, invalidSession("start time must be set") + case input.AbsoluteLifetime <= 0: + return Session{}, invalidSession("absolute lifetime must be positive") + } + id, err := uuid.NewV7() + if err != nil { + return Session{}, fmt.Errorf("domain.NewSession - generate session ID: %w", err) + } + return Session{ + ID: id, + UserID: input.UserID, + TokenHash: input.TokenHash, + CreatedAt: input.StartedAt, + LastSeenAt: input.StartedAt, + ExpiresAt: input.StartedAt.Add(input.AbsoluteLifetime), + }, nil +} + +func invalidSession(reason string) error { + return fmt.Errorf("domain.NewSession - %s: %w", reason, ErrInvalidSession) +} diff --git a/backend/internal/domain/session_test.go b/backend/internal/domain/session_test.go new file mode 100644 index 0000000..bd32973 --- /dev/null +++ b/backend/internal/domain/session_test.go @@ -0,0 +1,46 @@ +package domain + +import ( + "errors" + "testing" + "time" + + "github.com/google/uuid" +) + +func TestNewSessionSetsDeadlines(t *testing.T) { + input := NewSessionInput{ + UserID: uuid.New(), + TokenHash: testTokenHash(t), + StartedAt: testRegisteredAt, + AbsoluteLifetime: 7 * 24 * time.Hour, + } + session, err := NewSession(input) + if err != nil { + t.Fatalf("NewSession() error = %v", err) + } + if session.ID.Version() != 7 || session.UserID != input.UserID || session.TokenHash != input.TokenHash || + !session.CreatedAt.Equal(testRegisteredAt) || !session.LastSeenAt.Equal(testRegisteredAt) || + !session.ExpiresAt.Equal(testRegisteredAt.Add(7*24*time.Hour)) || session.RevokedAt != nil { + t.Fatalf("NewSession() = %+v", session) + } +} + +func TestNewSessionRejectsInvalidInput(t *testing.T) { + valid := NewSessionInput{UserID: uuid.New(), TokenHash: testTokenHash(t), StartedAt: testRegisteredAt, AbsoluteLifetime: time.Hour} + tests := map[string]func(*NewSessionInput){ + "nil user": func(input *NewSessionInput) { input.UserID = uuid.Nil }, + "zero hash": func(input *NewSessionInput) { input.TokenHash = SecretTokenHash{} }, + "zero start": func(input *NewSessionInput) { input.StartedAt = time.Time{} }, + "non-positive lifetime": func(input *NewSessionInput) { input.AbsoluteLifetime = -time.Second }, + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + input := valid + mutate(&input) + if _, err := NewSession(input); !errors.Is(err, ErrInvalidSession) { + t.Fatalf("NewSession() error = %v, want ErrInvalidSession", err) + } + }) + } +} diff --git a/backend/internal/domain/user.go b/backend/internal/domain/user.go new file mode 100644 index 0000000..574c113 --- /dev/null +++ b/backend/internal/domain/user.go @@ -0,0 +1,255 @@ +package domain + +import ( + "encoding/base64" + "errors" + "fmt" + "log/slog" + "regexp" + "time" + + "github.com/google/uuid" +) + +const ( + // maxPasswordHashLength bounds a PHC string. Encoded Argon2id hashes with + // common parameters stay near 100 bytes. + maxPasswordHashLength = 512 + // minPasswordSaltBytes and minPasswordDigestBytes follow the RFC 9106 + // recommendations of a 16-byte salt and a 32-byte tag, relaxed to bounds + // that still reject truncated or placeholder values. + minPasswordSaltBytes = 8 + minPasswordDigestBytes = 16 +) + +// passwordHashPattern is the Argon2id PHC string format: version 19, memory, +// iterations, and parallelism, then the salt and the digest in unpadded +// standard base64. Argon2id is the only password hash the identity contract +// accepts. +var passwordHashPattern = regexp.MustCompile( + `^\$argon2id\$v=19\$m=[1-9][0-9]{0,9},t=[1-9][0-9]{0,9},p=[1-9][0-9]{0,2}\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)$`, +) + +var ( + ErrInvalidUser = errors.New("invalid user") + ErrInvalidPasswordHash = errors.New("invalid password hash") + ErrEmailAlreadyVerified = errors.New("email already verified") +) + +// Scenario is the account scenario chosen at registration. Values match the +// AccountScenario schema of the public contract. +type Scenario string + +const ( + ScenarioCandidate Scenario = "candidate" + ScenarioEmployer Scenario = "employer" +) + +// ParseScenario accepts a value of the AccountScenario contract enum. +func ParseScenario(value string) (Scenario, error) { + scenario := Scenario(value) + switch scenario { + case ScenarioCandidate, ScenarioEmployer: + return scenario, nil + default: + return "", fmt.Errorf("domain.ParseScenario - unknown scenario: %w", ErrInvalidUser) + } +} + +// InitialOnboardingStep is the step a new or re-registered account starts at. +func (scenario Scenario) InitialOnboardingStep() OnboardingStep { + if scenario == ScenarioEmployer { + return OnboardingStepEmployerCompany + } + return OnboardingStepCandidateConsents +} + +// AllowsStep reports whether step belongs to the scenario's onboarding. +func (scenario Scenario) AllowsStep(step OnboardingStep) bool { + switch step { + case OnboardingStepCompleted: + return scenario == ScenarioCandidate || scenario == ScenarioEmployer + case OnboardingStepCandidateConsents, OnboardingStepCandidateProfile, + OnboardingStepCandidateQuestionnaire, OnboardingStepCandidateAssessment: + return scenario == ScenarioCandidate + case OnboardingStepEmployerCompany: + return scenario == ScenarioEmployer + default: + return false + } +} + +// OnboardingStep is the saved step the account returns to after login. Values +// match the OnboardingStep schema of the public contract. +type OnboardingStep string + +const ( + OnboardingStepCandidateConsents OnboardingStep = "candidate_consents" + OnboardingStepCandidateProfile OnboardingStep = "candidate_profile" + OnboardingStepCandidateQuestionnaire OnboardingStep = "candidate_questionnaire" + OnboardingStepCandidateAssessment OnboardingStep = "candidate_assessment" + OnboardingStepEmployerCompany OnboardingStep = "employer_company" + OnboardingStepCompleted OnboardingStep = "completed" +) + +// ParseOnboardingStep accepts a value of the OnboardingStep contract enum. +func ParseOnboardingStep(value string) (OnboardingStep, error) { + step := OnboardingStep(value) + switch step { + case OnboardingStepCandidateConsents, OnboardingStepCandidateProfile, OnboardingStepCandidateQuestionnaire, + OnboardingStepCandidateAssessment, OnboardingStepEmployerCompany, OnboardingStepCompleted: + return step, nil + default: + return "", fmt.Errorf("domain.ParseOnboardingStep - unknown onboarding step: %w", ErrInvalidUser) + } +} + +// PasswordHash is an Argon2id hash in the PHC string format. It is never the +// password itself. String and LogValue redact it. +type PasswordHash struct { + phc string +} + +// NewPasswordHash validates the structure of a PHC string produced by the +// password hasher, which also keeps a raw password from being stored by +// mistake. +func NewPasswordHash(phc string) (PasswordHash, error) { + if len(phc) > maxPasswordHashLength { + return PasswordHash{}, invalidPasswordHash("hash must have at most 512 bytes") + } + parts := passwordHashPattern.FindStringSubmatch(phc) + if parts == nil { + return PasswordHash{}, invalidPasswordHash("hash must be an Argon2id v19 PHC string") + } + salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[1]) + if err != nil || len(salt) < minPasswordSaltBytes { + return PasswordHash{}, invalidPasswordHash("salt must be unpadded base64 of at least 8 bytes") + } + digest, err := base64.RawStdEncoding.Strict().DecodeString(parts[2]) + if err != nil || len(digest) < minPasswordDigestBytes { + return PasswordHash{}, invalidPasswordHash("digest must be unpadded base64 of at least 16 bytes") + } + return PasswordHash{phc: phc}, nil +} + +func invalidPasswordHash(reason string) error { + return fmt.Errorf("domain.NewPasswordHash - %s: %w", reason, ErrInvalidPasswordHash) +} + +// PHC returns the encoded hash for storage and verification. +func (hash PasswordHash) PHC() string { return hash.phc } + +func (hash PasswordHash) String() string { return redactedSecret } + +func (hash PasswordHash) GoString() string { return redactedSecret } + +func (hash PasswordHash) LogValue() slog.Value { return slog.StringValue(redactedSecret) } + +// Format redacts every verb; without it %d would print the struct fields. +func (hash PasswordHash) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } + +// IsZero reports a PasswordHash not built by NewPasswordHash. +func (hash PasswordHash) IsZero() bool { return hash.phc == "" } + +// Registration is the validated content of one registration request. +type Registration struct { + Email EmailAddress + PasswordHash PasswordHash + Scenario Scenario + // RegisteredAt is the application clock at registration. The planned + // cleanup deletes an account that stays unverified past a deadline counted + // from the latest registration. + RegisteredAt time.Time +} + +func (registration Registration) validate(location string) error { + if registration.Email.IsZero() { + return fmt.Errorf("%s - email must be built by NewEmailAddress: %w", location, ErrInvalidUser) + } + if registration.PasswordHash.IsZero() { + return fmt.Errorf("%s - password hash must be built by NewPasswordHash: %w", location, ErrInvalidUser) + } + if _, err := ParseScenario(string(registration.Scenario)); err != nil { + return fmt.Errorf("%s - validate scenario: %w", location, err) + } + if registration.RegisteredAt.IsZero() { + return fmt.Errorf("%s - registration time must be set: %w", location, ErrInvalidUser) + } + return nil +} + +// User is an account. Storage reconstructs it from trusted rows; new accounts +// come from NewUser and changes from its methods. +type User struct { + ID uuid.UUID + Email EmailAddress + PasswordHash PasswordHash + Scenario Scenario + // OnboardingStep always belongs to Scenario (see Scenario.AllowsStep). + OnboardingStep OnboardingStep + EmailVerifiedAt *time.Time + // RegistrationVersion starts at 1 and advances on every registration of + // the still unverified email. Email tokens are bound to the version they + // were issued for, so a token from an earlier registration never confirms + // newer credentials. + RegistrationVersion int64 + LastRegisteredAt time.Time + // Version is the optimistic concurrency version. Storage advances it on + // every update and accepts an update only from the version it was read at. + Version int64 + CreatedAt time.Time + UpdatedAt time.Time +} + +// NewUser creates an unverified account at the scenario's first onboarding +// step with a time-ordered UUIDv7 identifier. +func NewUser(registration Registration) (User, error) { + if err := registration.validate("domain.NewUser"); err != nil { + return User{}, err + } + id, err := uuid.NewV7() + if err != nil { + return User{}, fmt.Errorf("domain.NewUser - generate user ID: %w", err) + } + return User{ + ID: id, + Email: registration.Email, + PasswordHash: registration.PasswordHash, + Scenario: registration.Scenario, + OnboardingStep: registration.Scenario.InitialOnboardingStep(), + RegistrationVersion: 1, + LastRegisteredAt: registration.RegisteredAt, + Version: 1, + CreatedAt: registration.RegisteredAt, + UpdatedAt: registration.RegisteredAt, + }, nil +} + +// EmailVerified reports whether the email has been confirmed. +func (user User) EmailVerified() bool { return user.EmailVerifiedAt != nil } + +// ReRegister applies a new registration of the same unverified email. It +// replaces the delivery form of the email, the password hash, the scenario, +// and the onboarding step. Version and RegistrationVersion are left unchanged: +// storage checks Version as the expected version, advances both in the same +// statement, and returns the stored account. A verified account returns +// ErrEmailAlreadyVerified and does not change. +func (user User) ReRegister(registration Registration) (User, error) { + if err := registration.validate("User.ReRegister"); err != nil { + return User{}, err + } + if user.EmailVerified() { + return User{}, fmt.Errorf("User.ReRegister - re-register account: %w", ErrEmailAlreadyVerified) + } + if registration.Email.Normalized() != user.Email.Normalized() { + return User{}, fmt.Errorf("User.ReRegister - email must match the account email: %w", ErrInvalidUser) + } + updated := user + updated.Email = registration.Email + updated.PasswordHash = registration.PasswordHash + updated.Scenario = registration.Scenario + updated.OnboardingStep = registration.Scenario.InitialOnboardingStep() + updated.LastRegisteredAt = registration.RegisteredAt + updated.UpdatedAt = registration.RegisteredAt + return updated, nil +} diff --git a/backend/internal/domain/user_test.go b/backend/internal/domain/user_test.go new file mode 100644 index 0000000..f53fabc --- /dev/null +++ b/backend/internal/domain/user_test.go @@ -0,0 +1,211 @@ +package domain + +import ( + "errors" + "fmt" + "strings" + "testing" + "time" +) + +const testPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA" + +var testRegisteredAt = time.Date(2026, time.October, 5, 12, 0, 0, 0, time.UTC) + +func testRegistration(t *testing.T, rawEmail string, scenario Scenario) Registration { + t.Helper() + email, err := NewEmailAddress(rawEmail) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + passwordHash, err := NewPasswordHash(testPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + return Registration{Email: email, PasswordHash: passwordHash, Scenario: scenario, RegisteredAt: testRegisteredAt} +} + +func TestParseScenarioAndOnboardingStepAcceptContractValues(t *testing.T) { + for _, value := range []string{"candidate", "employer"} { + if scenario, err := ParseScenario(value); err != nil || string(scenario) != value { + t.Fatalf("ParseScenario(%q) = %q, %v", value, scenario, err) + } + } + for _, value := range []string{ + "candidate_consents", "candidate_profile", "candidate_questionnaire", + "candidate_assessment", "employer_company", "completed", + } { + if step, err := ParseOnboardingStep(value); err != nil || string(step) != value { + t.Fatalf("ParseOnboardingStep(%q) = %q, %v", value, step, err) + } + } + for _, value := range []string{"", "Candidate", "admin"} { + if _, err := ParseScenario(value); !errors.Is(err, ErrInvalidUser) { + t.Fatalf("ParseScenario(%q) error = %v, want ErrInvalidUser", value, err) + } + if _, err := ParseOnboardingStep(value); !errors.Is(err, ErrInvalidUser) { + t.Fatalf("ParseOnboardingStep(%q) error = %v, want ErrInvalidUser", value, err) + } + } +} + +func TestScenarioOnboardingSteps(t *testing.T) { + tests := []struct { + scenario Scenario + initial OnboardingStep + allowed []OnboardingStep + denied []OnboardingStep + }{ + { + scenario: ScenarioCandidate, + initial: OnboardingStepCandidateConsents, + allowed: []OnboardingStep{ + OnboardingStepCandidateConsents, OnboardingStepCandidateProfile, OnboardingStepCandidateQuestionnaire, + OnboardingStepCandidateAssessment, OnboardingStepCompleted, + }, + denied: []OnboardingStep{OnboardingStepEmployerCompany, "unknown"}, + }, + { + scenario: ScenarioEmployer, + initial: OnboardingStepEmployerCompany, + allowed: []OnboardingStep{OnboardingStepEmployerCompany, OnboardingStepCompleted}, + denied: []OnboardingStep{OnboardingStepCandidateConsents, OnboardingStepCandidateAssessment, "unknown"}, + }, + } + for _, test := range tests { + if got := test.scenario.InitialOnboardingStep(); got != test.initial { + t.Fatalf("%s.InitialOnboardingStep() = %q, want %q", test.scenario, got, test.initial) + } + for _, step := range test.allowed { + if !test.scenario.AllowsStep(step) { + t.Fatalf("%s.AllowsStep(%q) = false, want true", test.scenario, step) + } + } + for _, step := range test.denied { + if test.scenario.AllowsStep(step) { + t.Fatalf("%s.AllowsStep(%q) = true, want false", test.scenario, step) + } + } + } +} + +func TestNewPasswordHashAcceptsOnlyArgon2idPHC(t *testing.T) { + for _, value := range []string{ + testPasswordHash, + "$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHRzb21lc2FsdA$RdescudvJCsgt3ub+b+dWRWJTmaaJObG", + } { + if _, err := NewPasswordHash(value); err != nil { + t.Fatalf("NewPasswordHash(%.30q) error = %v", value, err) + } + } + for name, value := range map[string]string{ + "empty": "", + "raw password": "correct horse battery staple", + "bcrypt": "$2b$12$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ01234", + "argon2i": "$argon2i$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "prefix only": "$argon2id$", + "old version": "$argon2id$v=16$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "missing parameter": "$argon2id$v=19$m=19456,t=2$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "zero memory": "$argon2id$v=19$m=0,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "padded salt": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHQ=$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "short salt": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "short digest": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaA", + "impossible base64": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0a$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA", + "url-safe alphabet": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGF_aGhhc2hoYXNoaGFzaA", + "trailing space": testPasswordHash + " ", + "trailing newline": testPasswordHash + "\n", + "extra segment": testPasswordHash + "$extra", + "too long": "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$" + strings.Repeat("a", maxPasswordHashLength), + } { + if _, err := NewPasswordHash(value); !errors.Is(err, ErrInvalidPasswordHash) { + t.Fatalf("NewPasswordHash(%s) error = %v, want ErrInvalidPasswordHash", name, err) + } + } +} + +func TestNewUserStartsUnverifiedAtTheFirstStep(t *testing.T) { + registration := testRegistration(t, "Employer@Example.com", ScenarioEmployer) + user, err := NewUser(registration) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if user.ID.Version() != 7 { + t.Fatalf("ID version = %d, want UUIDv7", user.ID.Version()) + } + if user.EmailVerified() || user.OnboardingStep != OnboardingStepEmployerCompany || + user.RegistrationVersion != 1 || user.Version != 1 { + t.Fatalf("NewUser() = %+v, want an unverified employer at employer_company with versions 1", user) + } + if !user.LastRegisteredAt.Equal(testRegisteredAt) || !user.CreatedAt.Equal(testRegisteredAt) || !user.UpdatedAt.Equal(testRegisteredAt) { + t.Fatalf("NewUser() timestamps = %v, %v, %v, want the registration time", user.LastRegisteredAt, user.CreatedAt, user.UpdatedAt) + } +} + +func TestNewUserRejectsIncompleteRegistration(t *testing.T) { + valid := testRegistration(t, "candidate@example.com", ScenarioCandidate) + tests := map[string]func(*Registration){ + "zero email": func(registration *Registration) { registration.Email = EmailAddress{} }, + "zero password hash": func(registration *Registration) { registration.PasswordHash = PasswordHash{} }, + "unknown scenario": func(registration *Registration) { registration.Scenario = "admin" }, + "zero time": func(registration *Registration) { registration.RegisteredAt = time.Time{} }, + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + registration := valid + mutate(®istration) + if _, err := NewUser(registration); !errors.Is(err, ErrInvalidUser) { + t.Fatalf("NewUser() error = %v, want ErrInvalidUser", err) + } + }) + } +} + +func TestReRegisterReplacesTheRegistrationOfAnUnverifiedAccount(t *testing.T) { + user, err := NewUser(testRegistration(t, "candidate@example.com", ScenarioCandidate)) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + user.OnboardingStep = OnboardingStepCandidateProfile + again := testRegistration(t, "Candidate@Example.com", ScenarioEmployer) + again.RegisteredAt = testRegisteredAt.Add(time.Hour) + + updated, err := user.ReRegister(again) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + if updated.ID != user.ID || updated.Email.Address() != "Candidate@Example.com" || + updated.Scenario != ScenarioEmployer || updated.OnboardingStep != OnboardingStepEmployerCompany || + updated.RegistrationVersion != user.RegistrationVersion || updated.Version != user.Version || + !updated.LastRegisteredAt.Equal(again.RegisteredAt) || !updated.UpdatedAt.Equal(again.RegisteredAt) || + !updated.CreatedAt.Equal(user.CreatedAt) { + t.Fatalf("ReRegister() = %+v", updated) + } +} + +func TestReRegisterRejectsVerifiedOrDifferentEmail(t *testing.T) { + user, err := NewUser(testRegistration(t, "candidate@example.com", ScenarioCandidate)) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if _, err := user.ReRegister(testRegistration(t, "other@example.com", ScenarioCandidate)); !errors.Is(err, ErrInvalidUser) { + t.Fatalf("ReRegister(other email) error = %v, want ErrInvalidUser", err) + } + verifiedAt := testRegisteredAt.Add(time.Minute) + user.EmailVerifiedAt = &verifiedAt + if _, err := user.ReRegister(testRegistration(t, "candidate@example.com", ScenarioCandidate)); !errors.Is(err, ErrEmailAlreadyVerified) { + t.Fatalf("ReRegister(verified) error = %v, want ErrEmailAlreadyVerified", err) + } +} + +func TestFormattedUserHidesEmailAndPasswordHash(t *testing.T) { + user, err := NewUser(testRegistration(t, "Private.Person@Example.com", ScenarioCandidate)) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + formatted := fmt.Sprintf("%v %+v %#v", user, user, user) + for _, secret := range []string{"Private", "private", "example.com", testPasswordHash, "argon2id"} { + if strings.Contains(formatted, secret) { + t.Fatalf("formatted user exposes %q: %s", secret, formatted) + } + } +} diff --git a/backend/internal/port/outbound/identity.go b/backend/internal/port/outbound/identity.go new file mode 100644 index 0000000..9bf69ca --- /dev/null +++ b/backend/internal/port/outbound/identity.go @@ -0,0 +1,165 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrUserNotFound reports that no account matches, including an insert + // that references an account deleted in the meantime. + ErrUserNotFound = errors.New("user not found") + + // ErrEmailTaken reports that another account already has the same + // normalized email. + ErrEmailTaken = errors.New("email already registered") + + // ErrUserVersionConflict reports that a conditional account update matched + // no row: the expected version is stale, the email is already verified, + // or the registration version has moved on. Read the account again. + ErrUserVersionConflict = errors.New("user changed concurrently") + + // ErrTokenHashConflict reports a second token or session with the same + // hash. With 256-bit random tokens it signals a broken generator, not a + // retryable condition. + ErrTokenHashConflict = errors.New("token hash already stored") + + // ErrEmailTokenNotFound reports that no token of the purpose has the hash. + ErrEmailTokenNotFound = errors.New("email token not found") + + // ErrEmailTokenConsumed reports a token that was already consumed. + ErrEmailTokenConsumed = errors.New("email token already consumed") + + // ErrEmailTokenInvalidated reports a token replaced by a later resend or + // re-registration, or issued for an earlier registration version. + ErrEmailTokenInvalidated = errors.New("email token invalidated") + + // ErrEmailTokenExpired reports a token past its lifetime that was neither + // consumed nor invalidated. + ErrEmailTokenExpired = errors.New("email token expired") + + // ErrSessionNotFound reports a session that does not exist, is revoked, + // is past its absolute deadline, or is idle longer than the timeout. + ErrSessionNotFound = errors.New("session not found") +) + +// IdentityRepositories exposes the identity repositories. UnitOfWork binds +// them to one transaction; an adapter may also provide them outside a +// transaction, where every call is its own statement. Every method that takes +// a time rejects the zero time. +// +// Lock order: an operation that changes both an account and its email tokens +// locks the tokens first and the account second, as Consume and +// MarkEmailVerified do in a confirmation. A re-registration or a resend +// therefore calls InvalidateActive before UpdateRegistration or Insert; the +// opposite order can deadlock against a concurrent confirmation. The only +// exception is DeleteUnverifiedRegisteredBefore, which locks the account +// before its tokens and sessions; it is safe because every lock it takes uses +// SKIP LOCKED and never waits. A deadlock that still happens, for example +// between callers that ignore this order, aborts one transaction with +// ErrTransactionConflict, and the caller may retry it. +type IdentityRepositories interface { + Users() UserRepository + EmailTokens() EmailTokenRepository + Sessions() SessionRepository +} + +// UserRepository stores accounts. Lookups by email use the normalized form. +type UserRepository interface { + // Create returns an error wrapping ErrEmailTaken when the normalized email + // already belongs to an account. + Create(ctx context.Context, user domain.User) error + + // GetByID returns ErrUserNotFound when no account has the ID. + GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) + + // GetByEmail returns ErrUserNotFound when no account has the normalized + // email. + GetByEmail(ctx context.Context, email domain.EmailAddress) (domain.User, error) + + // UpdateRegistration stores user as returned by domain.User.ReRegister. + // It applies only when the stored version still equals user.Version and + // the email is unverified. The same statement advances Version and + // RegistrationVersion by one, so callers never choose the registration + // version; the returned account carries the new values. Otherwise it + // returns ErrUserVersionConflict. + UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error) + + // MarkEmailVerified sets the verification time when the account is still + // unverified and still has registrationVersion, and returns the stored + // account. Otherwise it returns ErrUserVersionConflict. A confirmation + // calls it after EmailTokenRepository.Consume in the same transaction; see + // Consume. + MarkEmailVerified(ctx context.Context, id uuid.UUID, registrationVersion int64, at time.Time) (domain.User, error) + + // DeleteUnverifiedRegisteredBefore deletes at most limit accounts that are + // unverified and were last registered before cutoff, oldest first, with + // their tokens and sessions, and returns how many it deleted. It never + // waits for a lock: an account whose row, token, or session is locked by + // another transaction is skipped and stays for the next run. A cleanup job + // repeats it until the result is below limit and runs again later. + DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error) +} + +// EmailTokenRepository stores email token hashes. It never receives a raw +// token. +type EmailTokenRepository interface { + // Insert returns ErrUserNotFound when the account does not exist and + // ErrTokenHashConflict for a duplicate hash. + Insert(ctx context.Context, token domain.EmailToken) error + + // InvalidateActive marks every unconsumed, not yet invalidated token of + // the user and purpose as invalidated at the given time, and returns how + // many it marked. + InvalidateActive(ctx context.Context, userID uuid.UUID, purpose domain.EmailTokenPurpose, at time.Time) (int64, error) + + // Consume atomically marks the token consumed at the given time and + // returns it. Of concurrent calls with the same hash exactly one succeeds; + // the others wait for its transaction and then fail. It fails with + // ErrEmailTokenNotFound, ErrEmailTokenConsumed, ErrEmailTokenInvalidated, + // or ErrEmailTokenExpired, in that order of precedence. + // + // Consume compares the token's registration version with the account only + // as its statement reads the account, without locking it, so a + // re-registration that commits right after it is not detected. Binding the + // token to the current registration therefore requires a confirmation to + // call Users().MarkEmailVerified(token.UserID, token.RegistrationVersion) + // in the same transaction and to roll back when it returns + // ErrUserVersionConflict; the rollback also restores the token. The + // confirmation usecase maps that outcome to verification_token_invalid. + Consume(ctx context.Context, hash domain.SecretTokenHash, purpose domain.EmailTokenPurpose, at time.Time) (domain.EmailToken, error) +} + +// SessionRepository stores server-side sessions by the hash of their token. +type SessionRepository interface { + // Create returns ErrUserNotFound when the account does not exist and + // ErrTokenHashConflict for a duplicate hash. + Create(ctx context.Context, session domain.Session) error + + // FindActive returns the session with the hash when it is not revoked, + // its absolute deadline is after at, and it was last seen less than + // idleTimeout before at. Otherwise it returns ErrSessionNotFound. + FindActive(ctx context.Context, hash domain.SecretTokenHash, at time.Time, idleTimeout time.Duration) (domain.Session, error) + + // Touch records activity at the given time on a session that is still + // active by the same rules as FindActive and returns ErrSessionNotFound + // when it is not. To avoid a write on every request, the adapter stores + // the new time only when the stored last_seen_at is at least a short + // interval older (one minute in PostgreSQL), so the idle timeout can end + // a session up to that interval early. last_seen_at never moves back. + Touch(ctx context.Context, id uuid.UUID, at time.Time, idleTimeout time.Duration) error + + // Revoke revokes the session at the given time. It returns + // ErrSessionNotFound when the session does not exist or is already + // revoked. + Revoke(ctx context.Context, id uuid.UUID, at time.Time) error + + // RevokeAllForUser revokes every unrevoked session of the user and returns + // how many it revoked. + RevokeAllForUser(ctx context.Context, userID uuid.UUID, at time.Time) (int64, error) +} diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index 34f69b6..3b4d3f0 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -17,13 +17,22 @@ var ( // transaction callback. Nested calls would silently use a second connection // and commit independently of the outer transaction. ErrNestedTransaction = errors.New("transaction already in progress") + + // ErrTransactionConflict reports that PostgreSQL aborted the work with a + // deadlock (SQLSTATE 40P01) or a serialization failure (40001). Nothing + // was committed. The caller may retry the whole operation, ideally with a + // short backoff and a bounded number of attempts; a usecase or job that + // retries must stay idempotent. + ErrTransactionConflict = errors.New("transaction conflict") ) // Transactor runs a business operation in one database transaction. type Transactor interface { // WithinTransaction commits when fn returns nil and rolls back when fn - // returns an error or panics. The error is returned unchanged in identity - // and a panic is re-raised after the rollback. fn must use only the + // returns an error or panics. The error keeps its identity for errors.Is + // and errors.As; a deadlock or serialization failure, from fn or from the + // commit, additionally matches ErrTransactionConflict. A panic is + // re-raised after the rollback. fn must use only the // UnitOfWork and context it receives and must not retain them after // returning. Calling WithinTransaction with that context returns // ErrNestedTransaction. After a database error inside fn the transaction is @@ -39,6 +48,7 @@ type Transactor interface { // UnitOfWork exposes repositories bound to one transaction. Product // repositories are added here as their usecases appear. type UnitOfWork interface { + IdentityRepositories Outbox() OutboxWriter } diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index e94302e..4800c18 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -107,10 +107,10 @@ backend/ cmd/app/main.go calls bootstrap.Run and reports errors config/ shared runtime configuration internal/ - domain/ flat package; DomainEvent for the outbox + domain/ flat package; DomainEvent, identity types usecase/health/ operational readiness usecase port/inbound/ readiness input boundary - port/outbound/ readiness, cache, object storage, transaction, and outbox boundaries + port/outbound/ readiness, cache, object storage, transaction, outbox, and identity boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -119,22 +119,22 @@ backend/ router.go chi composition adapter/secondary/ ml/api/ generated client from backend/codegen/ogen-ml.yml - postgres/ pool, migrator, transactor, outbox writer, health check + postgres/ pool, migrator, transactor, outbox writer, identity 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 table, no product schema yet + db/ embedded migrations and SQL queries; outbox and identity 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. +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`. Product domain types and usecase modules, mail/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, a Redis cache adapter, and a SeaweedFS S3 adapter. Accounts, resumes, assessments, invitations, worker jobs, file workflows, mail, 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, a Redis cache adapter, and a SeaweedFS S3 adapter. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail, 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/`. @@ -227,6 +227,34 @@ Future FSP identity linking requires provider verification. A manually entered i The brief references Russian Federal Law 152-FZ. The system design calls for separate processing/publication consents, revocation, transfer controls for ML, and retention/deletion periods. Architecture documentation does not prove legal compliance. Agree on data handling before using real personal data; use synthetic profiles for the demo. +### Identity storage + +Implemented as storage only (TASK-051): migration `backend/db/migrations/00002_create_identity_tables.sql`, queries in `backend/db/queries/identity.sql`, domain types in `backend/internal/domain/`, ports in `backend/internal/port/outbound/identity.go`, and the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/identity.go`. The registration, verification, login, and session behavior described in [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf) is planned (TASK-053 to TASK-056); no usecase or handler uses this storage yet. + +- `users`: UUIDv7 `id`; `email`, the delivery form (trimmed ASCII, letter case as typed, returned as `Account.email`), and `email_normalized`, the unique comparison key (the same address with A-Z lowercased); `password_hash`, an Argon2id v19 PHC string; `scenario` and `onboarding_step` with a CHECK that the step belongs to the scenario; nullable `email_verified_at`; `registration_version`; `last_registered_at` with a partial index over unverified accounts for the planned 7-day cleanup; the optimistic `version`; `created_at` and `updated_at`. The delivery form is kept because RFC 5321 allows a case-sensitive local part: mail goes to the address as typed, while uniqueness ignores letter case. +- `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists the allowed purposes, so a password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. A CHECK allows at most one of consumed and invalidated. +- `sessions`: a UUIDv7 `id` that never leaves the server, `token_hash` (SHA-256 of the cookie value, unique), `user_id`, `created_at`, `last_seen_at`, the absolute `expires_at`, and `revoked_at`. No IP address or user agent is stored. +- Tokens and sessions reference `users` with `ON DELETE CASCADE`. The consent tables planned in TASK-062 can reference `users.id` the same way. CHECK constraints repeat the domain rules as a backstop: the ASCII address and its key, the PHC format, and timestamps (verification, consumption, invalidation, and revocation) not earlier than `created_at`. + +Decisions: + +- Email addresses are ASCII only, because the mailer has no SMTPUTF8 support. `domain.NewEmailAddress` rejects any non-ASCII character, including homoglyphs and fullwidth forms, with `ErrInvalidEmailAddress`, which the registration handler is expected to answer with 400 `validation_failed` whether or not an account exists. Internationalized domains are accepted only in their punycode form (`xn--...`). The key lowercases A-Z only; the database checks it with `translate()`, which does not depend on the collation, unlike `lower()`. Unicode addresses are future work: they need IDNA ToASCII for the domain, a rule for Unicode local parts, and SMTPUTF8 delivery. Rows are read back with `domain.RestoreEmailAddress`, which checks only that the address and key match, so a stricter rule later does not make existing accounts unreadable. +- The database stores hashes, never passwords or raw tokens. A token carries 256 bits from crypto/rand, so an unsalted SHA-256 cannot be reversed by guessing and a lookup stays one index probe; passwords need the slow Argon2id KDF instead. `bytea` keeps the digest at half the size of hex text, with an exact length CHECK and no letter-case variants. `domain.SecretToken`, `domain.PasswordHash`, and `domain.EmailAddress` redact themselves in `fmt` (every verb) and `slog` output, so printing a `domain.User` shows neither the address nor the hash; explicit accessors return the real values. Unmapped PostgreSQL errors from the identity repositories keep only the SQLSTATE and the constraint name, because the message and detail can quote row values. +- Enum-like columns are text with CHECK constraints rather than PostgreSQL enum types. A new scenario, step, or purpose replaces one constraint in a reversible migration; an enum value cannot be removed and cannot be used in the transaction that adds it. +- Every stored time comes from the application clock that the caller passes, so deadlines and the checks against them use one clock. Repositories reject the zero time. +- There is no CSRF column. `GetCurrentSession` must return the session's CSRF token after a reload, which a stored hash cannot reproduce. TASK-056 can derive the token from the session token with a server key, which needs no storage, or add a column in an additive migration. + +What the ports guarantee: + +- `UserRepository.Create` returns `ErrEmailTaken` for a duplicate key. `UpdateRegistration` stores the result of `domain.User.ReRegister` only when the stored `version` matches and the email is unverified; the same statement advances `version` and `registration_version` by one, so no caller chooses the registration version. `MarkEmailVerified` applies only to an unverified account with the given registration version. Both return `ErrUserVersionConflict` otherwise. +- `EmailTokenRepository.Consume` is one `UPDATE ... RETURNING` that requires an unconsumed, uninvalidated, unexpired token. Concurrent callers queue on the token row lock; under READ COMMITTED each waiter re-checks the row after the holder finishes, so exactly one succeeds and, if the holder rolls back, a waiter can still succeed. A miss is reported as `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (replaced, or issued for an earlier registration version), or `ErrEmailTokenExpired`. `InvalidateActive` marks every earlier token of a user and purpose. +- Consume compares the token's registration version with the account only as its statement reads the account, without locking it, so it cannot see a re-registration that commits right after it. The binding of a token to the current registration therefore holds only when a confirmation calls `MarkEmailVerified(token.UserID, token.RegistrationVersion)` in the same transaction and rolls back on `ErrUserVersionConflict`; the rollback also restores the token, which is then superseded. The confirmation usecase (TASK-054) maps that outcome to `verification_token_invalid`. +- `SessionRepository.FindActive` and `Touch` take the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout. `Touch` writes `last_seen_at` only when the stored value is more than one minute older, so frequent requests do not rewrite the row and the idle timeout can end a session up to a minute early; it never moves `last_seen_at` back or revives an ended session. `Revoke` and `RevokeAllForUser` set `revoked_at`. +- `DeleteUnverifiedRegisteredBefore` deletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, and their sessions with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token or session row, is locked by another transaction, such as a re-registration, a resend, or a confirmation; skipped accounts stay for the next run. +- `postgres.IdentityStore` runs the same repositories outside a transaction. Called with a context from a `Transactor` callback, it returns `ErrNestedTransaction` instead of committing on a separate connection. +- Unique and foreign key violations map to `ErrEmailTaken`, `ErrTokenHashConflict`, and `ErrUserNotFound` by SQLSTATE and constraint name, never by error text. +- Lock order: an operation that changes both an account and its tokens locks the tokens first. A confirmation consumes the token and then verifies the account, so a re-registration or resend calls `InvalidateActive` before it updates the account or inserts a token; the opposite order can deadlock. The cleanup is the only exception: it locks the account before the tokens and sessions, which is safe because each of those locks uses SKIP LOCKED and never waits. A deadlock (SQLSTATE 40P01) or serialization failure (40001) that still happens is reported by `Transactor.WithinTransaction` and the identity repositories as `outbound.ErrTransactionConflict`; nothing was committed, and the usecase or job may retry the whole operation with backoff while staying idempotent. + ## Frontend The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index e2224c4..f90825c 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -48,14 +48,14 @@ 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, and a 404 for an unknown API route; it does not start ML. -- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, and a transactor with the transactional outbox writer; Redis through go-cachekit, and SeaweedFS through the S3 API. 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, and sqlc-backed identity repositories for accounts, email tokens, and sessions; Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap. - 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 a home page, 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`). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the backend has no Go Kafka client, topics, or readiness check for Kafka. - 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, mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains only the outbox table and no business schema, product usecase and adapter directories 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, 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 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 @@ -159,6 +159,12 @@ For a local database, export `DATABASE_URL` in your shell and use these targets: The targets run `backend/cmd/migrate` with the same runner, lock, and timeouts as startup. The Makefile contains no connection strings; keep credentials out of committed files. Integration tests apply all migrations to the PostgreSQL container from the shared bootstrap; see [TESTING.md](TESTING.md). +### Identity storage + +Migration `00002_create_identity_tables.sql` creates `users`, `email_tokens`, and `sessions`; the queries are in `backend/db/queries/identity.sql`. The `outbound.UserRepository`, `EmailTokenRepository`, and `SessionRepository` ports are available through `UnitOfWork` inside `Transactor.WithinTransaction` and through `postgres.IdentityStore` outside a transaction. Nothing in bootstrap or the HTTP handlers uses them yet; registration, verification, login, and the session principal come in later tasks. + +The database never receives a password, a raw email token, or a raw session token. Repositories take a `domain.PasswordHash` (an Argon2id v19 PHC string) and a `domain.SecretTokenHash` (the SHA-256 of a `domain.SecretToken`). Email addresses are ASCII only for now; IDN and SMTPUTF8 support is future work that needs IDNA ToASCII for the domain. `SecretToken`, `PasswordHash`, and `EmailAddress` redact themselves in `fmt` and `slog` output; `SecretToken.Reveal` and `EmailAddress.Address` return the real values where they are needed. Every stored time comes from the application clock that the caller passes, and PostgreSQL keeps microseconds. A deadlock or serialization failure is reported as `outbound.ErrTransactionConflict`, and the caller may retry the whole operation. The schema and its decisions are described in [ARCHITECTURE.md](ARCHITECTURE.md#identity-storage). + ## 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/en/TESTING.md b/docs/en/TESTING.md index 43f1173..03882c7 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -36,7 +36,7 @@ Security checks run separately: `make -C security check` scans source/dependenci ## Current scaffold coverage -Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no accounts, assessments, search results, invitations, file workflows, or real model inference to validate as product behavior. +Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows and no real model inference to validate as product behavior. API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 6f2de92..5dce2b7 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -107,10 +107,10 @@ backend/ cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку config/ общая конфигурация runtime internal/ - domain/ плоский пакет; DomainEvent для outbox + domain/ плоский пакет; DomainEvent, типы identity usecase/health/ operational readiness usecase port/inbound/ inbound граница readiness - port/outbound/ границы readiness, кеша, объектного хранилища, транзакции и outbox + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox и identity adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -119,22 +119,22 @@ backend/ router.go сборка chi router adapter/secondary/ ml/api/ generated client из backend/codegen/ogen-ml.yml - postgres/ pool, migrator, transactor, запись outbox, 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, продуктовой схемы пока нет + db/ встроенные миграции и SQL-запросы; таблицы outbox и identity codegen/ конфигурация ogen и sqlc pkg/ резерв для обоснованных общих технических helpers ``` -Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. +Доменные типы лежат непосредственно в `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`. `domain/`, продуктовые `usecase/`, адаптеры почты и 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, Redis cache adapter и S3-адаптер SeaweedFS. Аккаунты, резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, Redis cache adapter и S3-адаптер SeaweedFS. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. @@ -227,6 +227,34 @@ contact_grant относится к паре кандидат-компания ТЗ ссылается на 152-ФЗ. Система должна иметь раздельные согласия на обработку и публикацию, отзыв, контроль передачи документов ML и сроки хранения/удаления. Описание архитектуры не является подтверждением юридического соответствия. До работы с настоящими данными нужны согласованные условия хранения и обработки; демонстрация использует синтетические профили. +### Хранение identity + +Реализовано только хранение (TASK-051): миграция `backend/db/migrations/00002_create_identity_tables.sql`, запросы в `backend/db/queries/identity.sql`, доменные типы в `backend/internal/domain/`, порты в `backend/internal/port/outbound/identity.go` и адаптер на sqlc в `backend/internal/adapter/secondary/postgres/identity.go`. Регистрация, подтверждение, вход и сессии из [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf) запланированы (TASK-053 - TASK-056); ни один usecase или обработчик это хранение пока не использует. + +- `users`: UUIDv7 `id`; `email` - форма для доставки (ASCII без пробелов по краям, регистр как при вводе, возвращается в `Account.email`), и `email_normalized` - уникальный ключ сравнения (тот же адрес, в котором A-Z переведены в нижний регистр); `password_hash` - строка PHC Argon2id v19; `scenario` и `onboarding_step` с CHECK, что шаг относится к сценарию; nullable `email_verified_at`; `registration_version`; `last_registered_at` с частичным индексом по неподтвержденным аккаунтам для запланированной очистки через 7 дней; оптимистичная `version`; `created_at` и `updated_at`. Форма для доставки хранится, потому что RFC 5321 допускает local part с учетом регистра: письмо уходит на адрес в введенном виде, а уникальность не учитывает регистр. +- `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. CHECK допускает не больше одного из consumed и invalidated. +- `sessions`: UUIDv7 `id`, который не покидает сервер, `token_hash` (SHA-256 значения cookie, уникальный), `user_id`, `created_at`, `last_seen_at`, абсолютный `expires_at` и `revoked_at`. IP-адрес и user agent не хранятся. +- Токены и сессии ссылаются на `users` с `ON DELETE CASCADE`. Таблицы согласий, запланированные в TASK-062, могут ссылаться на `users.id` так же. CHECK-ограничения дублируют доменные правила как последнюю защиту: ASCII-адрес и его ключ, формат PHC и времена (подтверждения, погашения, аннулирования и отзыва) не раньше `created_at`. + +Решения: + +- Email-адреса принимаются только в ASCII, потому что отправка почты не поддерживает SMTPUTF8. `domain.NewEmailAddress` отклоняет любой символ вне ASCII, включая гомоглифы и полноширинные формы, с `ErrInvalidEmailAddress`; обработчик регистрации должен отвечать на это 400 `validation_failed` независимо от того, существует ли аккаунт. Интернационализированные домены принимаются только в punycode (`xn--...`). Ключ переводит в нижний регистр только A-Z; база проверяет его через `translate()`, который, в отличие от `lower()`, не зависит от collation. Поддержка Unicode-адресов - будущая работа: нужны IDNA ToASCII для домена, правило для Unicode в local part и доставка через SMTPUTF8. Строки читаются через `domain.RestoreEmailAddress`, который проверяет только соответствие адреса и ключа, поэтому более строгое правило в будущем не сделает существующие аккаунты нечитаемыми. +- База хранит хеши, а не пароли и исходные токены. Токен несет 256 бит из crypto/rand, поэтому SHA-256 без соли нельзя обратить перебором, а поиск остается одним обращением к индексу; для паролей нужен медленный KDF Argon2id. `bytea` вдвое компактнее hex-текста, допускает точную проверку длины и не имеет вариантов регистра. `domain.SecretToken`, `domain.PasswordHash` и `domain.EmailAddress` скрывают значение в выводе `fmt` (для любого verb) и `slog`, поэтому при печати `domain.User` не видны ни адрес, ни хеш; настоящие значения возвращают явные методы доступа. Неотображенные ошибки PostgreSQL из репозиториев identity сохраняют только SQLSTATE и имя ограничения, потому что текст и detail ошибки могут содержать значения строки. +- Колонки с перечислимыми значениями - text с CHECK, а не enum-типы PostgreSQL. Новый сценарий, шаг или назначение заменяет одно ограничение в обратимой миграции; значение enum нельзя удалить и нельзя использовать в транзакции, которая его добавила. +- Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, поэтому сроки и проверки по ним используют одни часы. Репозитории отклоняют нулевое время. +- Колонки для CSRF нет. `GetCurrentSession` должен вернуть CSRF-токен сессии после перезагрузки страницы, а сохраненный хеш не позволяет его восстановить. TASK-056 может выводить токен из токена сессии с серверным ключом, что не требует хранения, или добавить колонку аддитивной миграцией. + +Что гарантируют порты: + +- `UserRepository.Create` возвращает `ErrEmailTaken` для повторного ключа. `UpdateRegistration` сохраняет результат `domain.User.ReRegister`, только если сохраненная `version` совпадает и email не подтвержден; тот же запрос увеличивает `version` и `registration_version` на единицу, поэтому версию регистрации не выбирает вызывающий код. `MarkEmailVerified` применяется только к неподтвержденному аккаунту с указанной версией регистрации. В остальных случаях оба возвращают `ErrUserVersionConflict`. +- `EmailTokenRepository.Consume` - один `UPDATE ... RETURNING`, который требует непогашенный, неаннулированный и неистекший токен. Параллельные вызовы ждут в очереди на блокировку строки токена; при READ COMMITTED каждый ожидающий заново проверяет строку после завершения владельца блокировки, поэтому успешен ровно один, а если владелец откатился, ожидающий еще может погасить токен. Неудача сообщается как `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (заменен или выдан для более ранней версии регистрации) или `ErrEmailTokenExpired`. `InvalidateActive` помечает все прежние токены пользователя с этим назначением. +- Consume сравнивает версию регистрации токена с аккаунтом только в том виде, в каком его прочитал запрос, без блокировки, поэтому не видит повторную регистрацию, зафиксированную сразу после него. Привязка токена к текущей регистрации поэтому соблюдается, только если подтверждение вызывает `MarkEmailVerified(token.UserID, token.RegistrationVersion)` в той же транзакции и откатывает ее при `ErrUserVersionConflict`; откат возвращает и токен, который затем считается замененным. Usecase подтверждения (TASK-054) переводит этот исход в `verification_token_invalid`. +- `SessionRepository.FindActive` и `Touch` получают таймаут простоя от вызывающего кода и принимают только неотозванную сессию до ее абсолютного срока и в пределах таймаута простоя. `Touch` записывает `last_seen_at`, только если сохраненное значение старше более чем на минуту, поэтому частые запросы не переписывают строку, а таймаут простоя может завершить сессию на минуту раньше; `Touch` не сдвигает `last_seen_at` назад и не возобновляет завершенную сессию. `Revoke` и `RevokeAllForUser` устанавливают `revoked_at`. +- `DeleteUnverifiedRegisteredBefore` удаляет одну пачку неподтвержденных аккаунтов, начиная со старых, и никогда не ждет блокировку. Он блокирует аккаунты-кандидаты, их токены и сессии через `FOR UPDATE SKIP LOCKED` и пропускает каждый аккаунт, у которого строка аккаунта или любая строка токена или сессии заблокирована другой транзакцией, например повторной регистрацией, повторной отправкой или подтверждением; пропущенные аккаунты остаются до следующего запуска. +- `postgres.IdentityStore` выполняет те же репозитории вне транзакции. При вызове с контекстом из callback `Transactor` он возвращает `ErrNestedTransaction`, а не фиксирует изменения через отдельное соединение. +- Нарушения уникальности и внешних ключей переводятся в `ErrEmailTaken`, `ErrTokenHashConflict` и `ErrUserNotFound` по SQLSTATE и имени ограничения, а не по тексту ошибки. +- Порядок блокировок: операция, которая меняет и аккаунт, и его токены, сначала блокирует токены. Подтверждение гасит токен, а затем подтверждает аккаунт, поэтому повторная регистрация или повторная отправка вызывает `InvalidateActive` до обновления аккаунта или вставки токена; обратный порядок может привести к взаимной блокировке. Единственное исключение - очистка: она блокирует аккаунт раньше токенов и сессий, и это безопасно, потому что каждая из этих блокировок берется с SKIP LOCKED и никогда не ждет. Если взаимная блокировка (SQLSTATE 40P01) или ошибка сериализации (40001) все же случится, `Transactor.WithinTransaction` и репозитории identity сообщают ее как `outbound.ErrTransactionConflict`; ничего не зафиксировано, и usecase или job может повторить всю операцию с паузой, оставаясь идемпотентным. + ## Frontend Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index f5dcccf..88a3f35 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -48,14 +48,14 @@ 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 маршрута; ML он не запускает. -- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, и transactor с записью transactional outbox; Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. +- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox и репозитории identity на sqlc для аккаунтов, email-токенов и сессий; Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. - 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`). - Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в backend нет Go клиента Kafka, топиков и проверки Kafka в readiness. - 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), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть только таблица outbox и нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, 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). ## Установка и цикл работы @@ -159,6 +159,12 @@ goose выполняет каждую миграцию в отдельной т Цели запускают `backend/cmd/migrate` с тем же runner, блокировкой и таймаутами, что и старт сервиса. Makefile не содержит строк подключения; не храните учетные данные в коммитах. Интеграционные тесты применяют все миграции к контейнеру PostgreSQL из общего bootstrap; см. [TESTING.md](TESTING.md). +### Хранение identity + +Миграция `00002_create_identity_tables.sql` создает `users`, `email_tokens` и `sessions`; запросы лежат в `backend/db/queries/identity.sql`. Порты `outbound.UserRepository`, `EmailTokenRepository` и `SessionRepository` доступны через `UnitOfWork` внутри `Transactor.WithinTransaction` и через `postgres.IdentityStore` вне транзакции. Bootstrap и HTTP-обработчики их пока не используют; регистрация, подтверждение, вход и principal сессии появятся в следующих задачах. + +База данных никогда не получает пароль, исходный email-токен или исходный токен сессии. Репозитории принимают `domain.PasswordHash` (строку PHC Argon2id v19) и `domain.SecretTokenHash` (SHA-256 от `domain.SecretToken`). Email-адреса пока принимаются только в ASCII; поддержка IDN и SMTPUTF8 - будущая работа, для которой нужен IDNA ToASCII для домена. `SecretToken`, `PasswordHash` и `EmailAddress` скрывают значение в выводе `fmt` и `slog`; `SecretToken.Reveal` и `EmailAddress.Address` возвращают настоящие значения там, где они нужны. Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, а PostgreSQL хранит микросекунды. Взаимная блокировка или ошибка сериализации сообщается как `outbound.ErrTransactionConflict`, и вызывающий код может повторить всю операцию. Схема и принятые решения описаны в [ARCHITECTURE.md](ARCHITECTURE.md#хранение-identity). + ## Читаемость Go-кода - Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 23c0213..e1e86ea 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -36,7 +36,7 @@ make -C ml check-generated использует datamodel-code-generator --check ## Что покрывает текущий каркас -Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет пользователей, тестовых заданий, поисковой выдачи, приглашений, файлового workflow или реального model inference, которые можно было бы проверить как бизнес-результат. +Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами и нет реального model inference, которые можно было бы проверить как бизнес-результат. API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub. From 6153887eb5003a61140339f669efd75865ae6a91 Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 00:38:58 +0300 Subject: [PATCH 008/143] feat(mail): add MailSender port and explicit provider selection --- .env.example | 21 ++ backend/config/config.go | 27 +- backend/config/config_test.go | 11 + backend/config/mail.go | 240 ++++++++++++++++++ backend/config/mail_test.go | 206 +++++++++++++++ backend/integration_test/bootstrap_test.go | 4 + .../internal/adapter/secondary/mail/.gitkeep | 0 .../adapter/secondary/mail/disabled/sender.go | 30 +++ .../secondary/mail/disabled/sender_test.go | 57 +++++ backend/internal/bootstrap/app.go | 38 ++- backend/internal/bootstrap/mail.go | 48 ++++ backend/internal/bootstrap/mail_test.go | 186 ++++++++++++++ backend/internal/bootstrap/wire.go | 10 +- backend/internal/bootstrap/wire_gen.go | 7 +- backend/internal/port/outbound/mail.go | 181 +++++++++++++ backend/internal/port/outbound/mail_test.go | 98 +++++++ deploy/docker/docker-compose.yml | 10 + deploy/scripts/smoke.sh | 12 +- docs/en/ARCHITECTURE.md | 19 +- docs/en/DEPLOY.md | 22 ++ docs/en/DEVELOPMENT.md | 5 +- docs/en/TESTING.md | 2 +- docs/ru/ARCHITECTURE.md | 19 +- docs/ru/DEPLOY.md | 22 ++ docs/ru/DEVELOPMENT.md | 5 +- docs/ru/TESTING.md | 2 +- 26 files changed, 1253 insertions(+), 29 deletions(-) create mode 100644 backend/config/mail.go create mode 100644 backend/config/mail_test.go delete mode 100644 backend/internal/adapter/secondary/mail/.gitkeep create mode 100644 backend/internal/adapter/secondary/mail/disabled/sender.go create mode 100644 backend/internal/adapter/secondary/mail/disabled/sender_test.go create mode 100644 backend/internal/bootstrap/mail.go create mode 100644 backend/internal/bootstrap/mail_test.go create mode 100644 backend/internal/port/outbound/mail.go create mode 100644 backend/internal/port/outbound/mail_test.go diff --git a/.env.example b/.env.example index c0cdf6d..34904f9 100644 --- a/.env.example +++ b/.env.example @@ -19,6 +19,27 @@ SEAWEEDFS_BUCKET=lincodex # before the first start; changing it later stops Kafka from using the existing volume. KAFKA_CLUSTER_ID=SJv4PXUUSJGbK3eSPC57qA +# Mail. EMAIL_PROVIDER is required and selects exactly one transport: +# resend, smtp, or disabled. The working stand uses resend; this build has no +# Resend or SMTP transport yet, so both fail startup after their settings are +# validated. disabled sends nothing and reports the mail channel as +# unavailable; it never confirms an address or skips an account check. +EMAIL_PROVIDER=disabled +EMAIL_FROM=no-reply@example.com +EMAIL_TIMEOUT=10s +# Public origin for links in mail: https, or http only for a loopback host. +APP_PUBLIC_URL=http://localhost:8080 +# Read only when EMAIL_PROVIDER=resend. Keep the real key in the server +# environment only. +RESEND_API_KEY= +# Read only when EMAIL_PROVIDER=smtp. SMTP_TLS_MODE is starttls or tls; +# plaintext SMTP is not supported. +SMTP_HOST= +SMTP_PORT= +SMTP_USERNAME= +SMTP_PASSWORD= +SMTP_TLS_MODE= + # Optional PostgreSQL metrics login, created when the database volume is initialized. POSTGRES_EXPORTER_USER=metrics_reader POSTGRES_EXPORTER_PASSWORD=replace-this-metrics-password diff --git a/backend/config/config.go b/backend/config/config.go index d27bd55..3230330 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -41,9 +41,24 @@ type Config struct { SeaweedFSRegion string SeaweedFSTimeout time.Duration KafkaBrokers []string - LogLevel string - ReadinessTimeout time.Duration - ShutdownTimeout time.Duration + // EmailProvider selects the only active mail transport. Settings of the + // other transports are not loaded. + EmailProvider EmailProvider + // EmailFrom is the sender mailbox for every outgoing message. + EmailFrom string + EmailTimeout time.Duration + // AppPublicURL is the public origin without a trailing slash, for links + // in mail. + AppPublicURL string + ResendAPIKey string + SMTPHost string + SMTPPort int + SMTPUsername string + SMTPPassword string + SMTPTLSMode SMTPTLSMode + LogLevel string + ReadinessTimeout time.Duration + ShutdownTimeout time.Duration } type LookupEnv func(string) (string, bool) @@ -75,6 +90,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { if err := config.loadRedis(lookup); err != nil { return Config{}, err } + if err := config.loadMail(lookup); err != nil { + return Config{}, err + } var err error config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart) @@ -113,6 +131,9 @@ func (config Config) Validate() error { if err := config.ValidateKafka(); err != nil { return err } + if err := config.ValidateMail(); err != nil { + return err + } if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil { return err } diff --git a/backend/config/config_test.go b/backend/config/config_test.go index 6542b62..ec179cb 100644 --- a/backend/config/config_test.go +++ b/backend/config/config_test.go @@ -118,10 +118,21 @@ func testEnvironment(values map[string]string) LookupEnv { if key == "SEAWEEDFS_SECRET_KEY" { return "test-secret", true } + if value, ok := mailFixture[key]; ok { + return value, true + } return "", false } } +// mailFixture is the smallest valid mail configuration. Mail tests override +// or remove entries to cover each transport. +var mailFixture = map[string]string{ + "EMAIL_PROVIDER": "disabled", + "EMAIL_FROM": "Lincodex ", + "APP_PUBLIC_URL": "http://localhost:8080", +} + func TestLoadFromEnvSeaweedFS(t *testing.T) { settings, err := LoadFromEnv(testEnvironment(nil)) if err != nil { diff --git a/backend/config/mail.go b/backend/config/mail.go new file mode 100644 index 0000000..cb753e4 --- /dev/null +++ b/backend/config/mail.go @@ -0,0 +1,240 @@ +package config + +import ( + "errors" + "fmt" + "net" + "net/mail" + "net/url" + "strconv" + "strings" + "time" + + "lincodex/backend/internal/domain" +) + +// EmailProvider selects exactly one mail transport. There is no implicit +// fallback between transports. +type EmailProvider string + +const ( + EmailProviderResend EmailProvider = "resend" + EmailProviderSMTP EmailProvider = "smtp" + EmailProviderDisabled EmailProvider = "disabled" +) + +// SMTPTLSMode selects how the SMTP transport protects the connection. +// Plaintext SMTP is not supported. +type SMTPTLSMode string + +const ( + // SMTPTLSModeStartTLS upgrades the connection with STARTTLS and fails + // when the server does not offer it (submission, usually port 587). + SMTPTLSModeStartTLS SMTPTLSMode = "starttls" + // SMTPTLSModeImplicit opens TLS before the SMTP dialog (usually port 465). + SMTPTLSModeImplicit SMTPTLSMode = "tls" +) + +const ( + defaultEmailTimeout = 10 * time.Second + // One attempt waits at least long enough for a TLS handshake and an API + // answer, and at most one minute so that a hung provider cannot hold a + // delivery worker indefinitely. + minEmailTimeout = time.Second + maxEmailTimeout = time.Minute +) + +// loadMail reads the common mail settings and only the settings of the +// selected transport, so settings of an inactive transport, including its +// secrets, never reach Config. +// +// EMAIL_PROVIDER has no default. The working stand uses resend, but a default +// would either pick a transport that this build may not provide or silently +// turn mail off; an explicit choice makes both visible at deployment time. +func (config *Config) loadMail(lookup LookupEnv) error { + provider := strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "EMAIL_PROVIDER", ""))) + config.EmailProvider = EmailProvider(provider) + config.EmailFrom = strings.TrimSpace(valueOrDefault(lookup, "EMAIL_FROM", "")) + // One trailing slash is accepted and dropped so that the stored value is + // an origin that links can be appended to. + config.AppPublicURL = strings.TrimSuffix(strings.TrimSpace(valueOrDefault(lookup, "APP_PUBLIC_URL", "")), "/") + + var err error + config.EmailTimeout, err = durationOrDefault(lookup, "EMAIL_TIMEOUT", defaultEmailTimeout) + if err != nil { + return err + } + + switch config.EmailProvider { + case EmailProviderResend: + config.ResendAPIKey = valueOrDefault(lookup, "RESEND_API_KEY", "") + case EmailProviderSMTP: + return config.loadSMTP(lookup) + case EmailProviderDisabled: + // No transport settings are read. + } + return nil +} + +func (config *Config) loadSMTP(lookup LookupEnv) error { + config.SMTPHost = strings.TrimSpace(valueOrDefault(lookup, "SMTP_HOST", "")) + config.SMTPUsername = strings.TrimSpace(valueOrDefault(lookup, "SMTP_USERNAME", "")) + config.SMTPPassword = valueOrDefault(lookup, "SMTP_PASSWORD", "") + config.SMTPTLSMode = SMTPTLSMode(strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "SMTP_TLS_MODE", "")))) + + // An unset or empty port stays zero, which validation reports as missing. + port := strings.TrimSpace(valueOrDefault(lookup, "SMTP_PORT", "")) + if port == "" { + return nil + } + number, err := strconv.Atoi(port) + if err != nil { + return fmt.Errorf("Config.loadSMTP - SMTP_PORT must be an integer between 1 and %d", maxPortNumber) + } + config.SMTPPort = number + return nil +} + +// ValidateMail checks the common mail settings and the selected transport. +// Errors name the setting and never include secret values. +func (config Config) ValidateMail() error { + // The value is not echoed: a misplaced secret must not reach the logs. + switch config.EmailProvider { + case EmailProviderResend, EmailProviderSMTP, EmailProviderDisabled: + case "": + return errors.New("Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled") + default: + return errors.New("Config.ValidateMail - EMAIL_PROVIDER must be one of resend, smtp, or disabled") + } + if err := validateEmailFrom(config.EmailFrom); err != nil { + return err + } + if err := validateAppPublicURL(config.AppPublicURL); err != nil { + return err + } + if config.EmailTimeout < minEmailTimeout || config.EmailTimeout > maxEmailTimeout { + return fmt.Errorf("Config.ValidateMail - EMAIL_TIMEOUT must be between %s and %s", minEmailTimeout, maxEmailTimeout) + } + + switch config.EmailProvider { + case EmailProviderResend: + return validateResendAPIKey(config.ResendAPIKey) + case EmailProviderSMTP: + return config.validateSMTP() + case EmailProviderDisabled: + } + return nil +} + +// validateEmailFrom accepts one RFC 5322 mailbox, with or without a display +// name. The address itself follows the account address rules of +// domain.NewEmailAddress: ASCII only, because the mailer does not support +// SMTPUTF8, an unquoted local part, and a DNS domain with at least two labels. +func validateEmailFrom(raw string) error { + if raw == "" { + return errors.New("config.validateEmailFrom - EMAIL_FROM must be set") + } + // Control characters such as CR and LF could inject header lines. + if !isPrintableASCII(raw) { + return errors.New("config.validateEmailFrom - EMAIL_FROM must contain printable ASCII characters only") + } + mailbox, err := mail.ParseAddress(raw) + if err != nil { + return errors.New("config.validateEmailFrom - EMAIL_FROM must be one mailbox such as Lincodex ") + } + if _, err := domain.NewEmailAddress(mailbox.Address); err != nil { + return errors.New("config.validateEmailFrom - EMAIL_FROM address must be an ASCII addr-spec with a DNS domain of at least two labels") + } + return nil +} + +// validateAppPublicURL accepts the public origin that links in mail point +// to. Plain HTTP is accepted only for a loopback host in local runs. +func validateAppPublicURL(raw string) error { + if raw == "" { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be set") + } + origin, err := url.Parse(raw) + if err != nil || origin.Hostname() == "" || !validHostOrIP(origin.Hostname()) { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be an absolute URL with a valid host") + } + switch { + case origin.Scheme == "https": + case origin.Scheme == "http" && isLoopbackHost(origin.Hostname()): + default: + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must use https; http is allowed only for localhost, 127.0.0.1, or [::1]") + } + + if !isBareOrigin(origin, raw) { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be an origin without credentials, a path, query, or fragment") + } + if !validEndpointPort(origin) { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must have a valid nonzero port") + } + return nil +} + +// isBareOrigin reports a URL with nothing after the authority. raw is checked +// for "#" because url.Parse drops an empty fragment. +func isBareOrigin(origin *url.URL, raw string) bool { + hasCredentials := origin.User != nil + hasPath := origin.Path != "" || origin.RawPath != "" + hasQuery := origin.RawQuery != "" || origin.ForceQuery + hasFragment := origin.Fragment != "" || strings.Contains(raw, "#") + return !hasCredentials && !hasPath && !hasQuery && !hasFragment +} + +// validateResendAPIKey checks only what the Authorization header needs. Resend +// shows keys as "re_..." in examples but does not document a stable format, +// so the prefix is not enforced; the provider itself rejects a wrong key. +func validateResendAPIKey(key string) error { + if key == "" { + return errors.New("config.validateResendAPIKey - RESEND_API_KEY must be set when EMAIL_PROVIDER is resend") + } + if !isPrintableASCII(key) || strings.Contains(key, " ") { + return errors.New("config.validateResendAPIKey - RESEND_API_KEY must not contain whitespace or non-ASCII characters") + } + return nil +} + +func (config Config) validateSMTP() error { + if config.SMTPHost == "" { + return errors.New("Config.validateSMTP - SMTP_HOST must be set when EMAIL_PROVIDER is smtp") + } + if !validHostOrIP(config.SMTPHost) { + return errors.New("Config.validateSMTP - SMTP_HOST must be a hostname or IP address without a port") + } + if config.SMTPPort < 1 || config.SMTPPort > maxPortNumber { + return fmt.Errorf("Config.validateSMTP - SMTP_PORT must be set to a port between 1 and %d when EMAIL_PROVIDER is smtp", maxPortNumber) + } + // An anonymous relay is not supported: both credentials are required. + if config.SMTPUsername == "" { + return errors.New("Config.validateSMTP - SMTP_USERNAME must be set when EMAIL_PROVIDER is smtp") + } + if config.SMTPPassword == "" { + return errors.New("Config.validateSMTP - SMTP_PASSWORD must be set when EMAIL_PROVIDER is smtp") + } + switch config.SMTPTLSMode { + case SMTPTLSModeStartTLS, SMTPTLSModeImplicit: + return nil + default: + return errors.New("Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls; plaintext SMTP is not supported") + } +} + +func validHostOrIP(host string) bool { + return net.ParseIP(host) != nil || validHostname(host) +} + +func isLoopbackHost(host string) bool { + return strings.EqualFold(host, "localhost") || host == "127.0.0.1" || host == "::1" +} + +func isPrintableASCII(value string) bool { + for index := range len(value) { + if value[index] < ' ' || value[index] > '~' { + return false + } + } + return true +} diff --git a/backend/config/mail_test.go b/backend/config/mail_test.go new file mode 100644 index 0000000..ed5fb4f --- /dev/null +++ b/backend/config/mail_test.go @@ -0,0 +1,206 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +const ( + testResendAPIKey = "re_test-key-value" + testSMTPPassword = "smtp password value" + secretMarker = "hidden-secret-marker" + testSMTPHost = "smtp.example.com" + testPublicOrigin = "https://lincodex.example" + testSenderMailbox = "Lincodex " +) + +// mailEnvironment overrides mail settings on top of the shared test +// environment and removes the keys named in unset. +func mailEnvironment(values map[string]string, unset ...string) LookupEnv { + base := testEnvironment(values) + return func(key string) (string, bool) { + for _, removed := range unset { + if key == removed { + return "", false + } + } + return base(key) + } +} + +func smtpValues(overrides map[string]string) map[string]string { + values := map[string]string{ + "EMAIL_PROVIDER": "smtp", + "SMTP_HOST": testSMTPHost, + "SMTP_PORT": "587", + "SMTP_USERNAME": "mailer", + "SMTP_PASSWORD": testSMTPPassword, + "SMTP_TLS_MODE": "starttls", + } + for key, value := range overrides { + values[key] = value + } + return values +} + +func TestLoadFromEnvMailDisabledIgnoresTransportSettings(t *testing.T) { + settings, err := LoadFromEnv(mailEnvironment(map[string]string{ + "EMAIL_PROVIDER": " Disabled ", + "EMAIL_FROM": " " + testSenderMailbox + " ", + "APP_PUBLIC_URL": testPublicOrigin + "/", + "RESEND_API_KEY": testResendAPIKey, + "SMTP_HOST": testSMTPHost, + "SMTP_PORT": "not-a-port", + "SMTP_PASSWORD": testSMTPPassword, + "SMTP_TLS_MODE": "plaintext", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.EmailProvider != EmailProviderDisabled { + t.Fatalf("EmailProvider = %q, want disabled", settings.EmailProvider) + } + if settings.EmailFrom != testSenderMailbox || settings.AppPublicURL != testPublicOrigin { + t.Fatalf("EmailFrom = %q, AppPublicURL = %q", settings.EmailFrom, settings.AppPublicURL) + } + if settings.EmailTimeout != 10*time.Second { + t.Fatalf("EmailTimeout = %s, want the 10s default", settings.EmailTimeout) + } + if settings.ResendAPIKey != "" || settings.SMTPHost != "" || settings.SMTPPort != 0 || settings.SMTPPassword != "" || settings.SMTPTLSMode != "" { + t.Fatal("settings of an inactive transport were loaded") + } +} + +func TestLoadFromEnvMailResendLoadsOnlyResendSettings(t *testing.T) { + settings, err := LoadFromEnv(mailEnvironment(map[string]string{ + "EMAIL_PROVIDER": "RESEND", + "EMAIL_TIMEOUT": "15s", + "RESEND_API_KEY": testResendAPIKey, + "SMTP_HOST": testSMTPHost, + "SMTP_PASSWORD": testSMTPPassword, + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.EmailProvider != EmailProviderResend || settings.ResendAPIKey != testResendAPIKey || settings.EmailTimeout != 15*time.Second { + t.Fatalf("Resend settings were not loaded: provider=%q timeout=%s", settings.EmailProvider, settings.EmailTimeout) + } + if settings.SMTPHost != "" || settings.SMTPPassword != "" { + t.Fatal("SMTP settings were loaded for EMAIL_PROVIDER=resend") + } +} + +func TestLoadFromEnvMailSMTPLoadsOnlySMTPSettings(t *testing.T) { + settings, err := LoadFromEnv(mailEnvironment(smtpValues(map[string]string{ + "SMTP_PORT": " 465 ", + "SMTP_TLS_MODE": " TLS ", + "RESEND_API_KEY": testResendAPIKey, + }))) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.SMTPHost != testSMTPHost || settings.SMTPPort != 465 || settings.SMTPUsername != "mailer" || settings.SMTPPassword != testSMTPPassword || settings.SMTPTLSMode != SMTPTLSModeImplicit { + t.Fatal("SMTP settings were not loaded") + } + if settings.ResendAPIKey != "" { + t.Fatal("RESEND_API_KEY was loaded for EMAIL_PROVIDER=smtp") + } +} + +func TestLoadFromEnvAcceptsMailBoundaries(t *testing.T) { + tests := []struct { + name string + values map[string]string + }{ + {name: "bare sender address", values: map[string]string{"EMAIL_FROM": "no-reply@example.com"}}, + {name: "quoted display name", values: map[string]string{"EMAIL_FROM": `"Lincodex Team" `}}, + {name: "punycode sender domain", values: map[string]string{"EMAIL_FROM": "no-reply@xn--e1afmkfd.xn--p1ai"}}, + {name: "minimum timeout", values: map[string]string{"EMAIL_TIMEOUT": "1s"}}, + {name: "maximum timeout", values: map[string]string{"EMAIL_TIMEOUT": "60s"}}, + {name: "HTTPS origin with port", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example:8443"}}, + {name: "HTTP loopback IPv4", values: map[string]string{"APP_PUBLIC_URL": "http://127.0.0.1:8080"}}, + {name: "HTTP loopback IPv6", values: map[string]string{"APP_PUBLIC_URL": "http://[::1]:8080/"}}, + {name: "SMTP over STARTTLS", values: smtpValues(map[string]string{"SMTP_TLS_MODE": "STARTTLS"})}, + {name: "SMTP host as IP address", values: smtpValues(map[string]string{"SMTP_HOST": "10.0.0.25"})}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if _, err := LoadFromEnv(mailEnvironment(test.values)); err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + }) + } +} + +func TestLoadFromEnvRejectsMailSettings(t *testing.T) { + resend := func(key string) map[string]string { + return map[string]string{"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": key} + } + tests := []struct { + name string + values map[string]string + unset []string + want string + }{ + {name: "provider unset", unset: []string{"EMAIL_PROVIDER"}, want: "Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled"}, + {name: "provider empty", values: map[string]string{"EMAIL_PROVIDER": " "}, want: "Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled"}, + {name: "unknown provider", values: map[string]string{"EMAIL_PROVIDER": "sendgrid"}, want: "Config.ValidateMail - EMAIL_PROVIDER must be one of resend, smtp, or disabled"}, + {name: "secret pasted as provider", values: map[string]string{"EMAIL_PROVIDER": secretMarker}, want: "Config.ValidateMail - EMAIL_PROVIDER must be one of"}, + {name: "sender unset", unset: []string{"EMAIL_FROM"}, want: "config.validateEmailFrom - EMAIL_FROM must be set"}, + {name: "sender empty", values: map[string]string{"EMAIL_FROM": " "}, want: "config.validateEmailFrom - EMAIL_FROM must be set"}, + {name: "sender without domain", values: map[string]string{"EMAIL_FROM": "no-reply"}, want: "config.validateEmailFrom - EMAIL_FROM must be one mailbox"}, + {name: "sender list", values: map[string]string{"EMAIL_FROM": "a@example.com, b@example.com"}, want: "config.validateEmailFrom - EMAIL_FROM must be one mailbox"}, + {name: "sender header injection", values: map[string]string{"EMAIL_FROM": "a@example.com\r\nBcc: b@example.com"}, want: "config.validateEmailFrom - EMAIL_FROM must contain printable ASCII"}, + {name: "sender non-ASCII name", values: map[string]string{"EMAIL_FROM": "Линкодекс "}, want: "config.validateEmailFrom - EMAIL_FROM must contain printable ASCII"}, + {name: "sender single-label domain", values: map[string]string{"EMAIL_FROM": "no-reply@localhost"}, want: "config.validateEmailFrom - EMAIL_FROM address must be"}, + {name: "sender IP literal", values: map[string]string{"EMAIL_FROM": "no-reply@[127.0.0.1]"}, want: "config.validateEmailFrom - EMAIL_FROM address must be"}, + {name: "sender quoted local part", values: map[string]string{"EMAIL_FROM": `"no reply"@example.com`}, want: "config.validateEmailFrom - EMAIL_FROM address must be"}, + {name: "timeout unparsable", values: map[string]string{"EMAIL_TIMEOUT": "soon"}, want: "config.durationOrDefault - parse EMAIL_TIMEOUT"}, + {name: "timeout empty", values: map[string]string{"EMAIL_TIMEOUT": ""}, want: "config.durationOrDefault - parse EMAIL_TIMEOUT"}, + {name: "timeout zero", values: map[string]string{"EMAIL_TIMEOUT": "0s"}, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between 1s and 1m0s"}, + {name: "timeout too short", values: map[string]string{"EMAIL_TIMEOUT": "500ms"}, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between"}, + {name: "timeout too long", values: map[string]string{"EMAIL_TIMEOUT": "61s"}, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between"}, + {name: "public URL unset", unset: []string{"APP_PUBLIC_URL"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be set"}, + {name: "public URL without scheme", values: map[string]string{"APP_PUBLIC_URL": "lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an absolute URL"}, + {name: "public URL with space", values: map[string]string{"APP_PUBLIC_URL": "https://linco dex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an absolute URL"}, + {name: "public URL other scheme", values: map[string]string{"APP_PUBLIC_URL": "ftp://lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https"}, + {name: "public URL plain HTTP", values: map[string]string{"APP_PUBLIC_URL": "http://lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https"}, + {name: "public URL loopback lookalike", values: map[string]string{"APP_PUBLIC_URL": "http://localhost.lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https"}, + {name: "public URL credentials", values: map[string]string{"APP_PUBLIC_URL": "https://user:" + secretMarker + "@lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL path", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example/app"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL double slash", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example//"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL query", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example?token=" + secretMarker}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL fragment", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example#top"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL empty fragment", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example#"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL zero port", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example:0"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must have a valid nonzero port"}, + {name: "public URL port out of range", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example:70000"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must have a valid nonzero port"}, + {name: "Resend key unset", values: map[string]string{"EMAIL_PROVIDER": "resend"}, want: "config.validateResendAPIKey - RESEND_API_KEY must be set when EMAIL_PROVIDER is resend"}, + {name: "Resend key empty", values: resend(""), want: "config.validateResendAPIKey - RESEND_API_KEY must be set"}, + {name: "Resend key with space", values: resend("re_" + secretMarker + " x"), want: "config.validateResendAPIKey - RESEND_API_KEY must not contain whitespace"}, + {name: "Resend key with newline", values: resend("re_" + secretMarker + "\n"), want: "config.validateResendAPIKey - RESEND_API_KEY must not contain whitespace"}, + {name: "SMTP host unset", values: smtpValues(nil), unset: []string{"SMTP_HOST"}, want: "Config.validateSMTP - SMTP_HOST must be set when EMAIL_PROVIDER is smtp"}, + {name: "SMTP host with port", values: smtpValues(map[string]string{"SMTP_HOST": "smtp.example.com:587"}), want: "Config.validateSMTP - SMTP_HOST must be a hostname or IP address"}, + {name: "SMTP port unset", values: smtpValues(nil), unset: []string{"SMTP_PORT"}, want: "Config.validateSMTP - SMTP_PORT must be set to a port between 1 and 65535"}, + {name: "SMTP port not a number", values: smtpValues(map[string]string{"SMTP_PORT": "submission"}), want: "Config.loadSMTP - SMTP_PORT must be an integer"}, + {name: "SMTP port zero", values: smtpValues(map[string]string{"SMTP_PORT": "0"}), want: "Config.validateSMTP - SMTP_PORT must be set to a port"}, + {name: "SMTP port out of range", values: smtpValues(map[string]string{"SMTP_PORT": "70000"}), want: "Config.validateSMTP - SMTP_PORT must be set to a port"}, + {name: "SMTP username unset", values: smtpValues(nil), unset: []string{"SMTP_USERNAME"}, want: "Config.validateSMTP - SMTP_USERNAME must be set when EMAIL_PROVIDER is smtp"}, + {name: "SMTP password unset", values: smtpValues(nil), unset: []string{"SMTP_PASSWORD"}, want: "Config.validateSMTP - SMTP_PASSWORD must be set when EMAIL_PROVIDER is smtp"}, + {name: "SMTP TLS mode unset", values: smtpValues(nil), unset: []string{"SMTP_TLS_MODE"}, want: "Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls"}, + {name: "SMTP plaintext", values: smtpValues(map[string]string{"SMTP_TLS_MODE": "none"}), want: "Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls; plaintext SMTP is not supported"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := LoadFromEnv(mailEnvironment(test.values, test.unset...)) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want) + } + for _, secret := range []string{secretMarker, testResendAPIKey, testSMTPPassword} { + if strings.Contains(err.Error(), secret) { + t.Fatalf("configuration error discloses a configured value: %v", err) + } + } + }) + } +} diff --git a/backend/integration_test/bootstrap_test.go b/backend/integration_test/bootstrap_test.go index a3becac..006250c 100644 --- a/backend/integration_test/bootstrap_test.go +++ b/backend/integration_test/bootstrap_test.go @@ -86,6 +86,10 @@ func bootstrap(t *testing.T, services ...service) *testEnvironment { "SEAWEEDFS_SECRET_KEY": seaweedfsSecretKey, "SEAWEEDFS_BUCKET": seaweedfsBucket, "SEAWEEDFS_TIMEOUT": storageTimeout.String(), + // Integration tests send no mail; disabled is the explicit choice. + "EMAIL_PROVIDER": "disabled", + "EMAIL_FROM": "no-reply@example.com", + "APP_PUBLIC_URL": "http://localhost:8080", } settings, err := config.LoadFromEnv(func(key string) (string, bool) { value, ok := fixtures[key] diff --git a/backend/internal/adapter/secondary/mail/.gitkeep b/backend/internal/adapter/secondary/mail/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/backend/internal/adapter/secondary/mail/disabled/sender.go b/backend/internal/adapter/secondary/mail/disabled/sender.go new file mode 100644 index 0000000..97b5787 --- /dev/null +++ b/backend/internal/adapter/secondary/mail/disabled/sender.go @@ -0,0 +1,30 @@ +// Package disabled provides the mail transport for EMAIL_PROVIDER=disabled. +package disabled + +import ( + "context" + "fmt" + + "lincodex/backend/internal/port/outbound" +) + +// Sender sends nothing. Every valid message is reported as +// outbound.ErrMailChannelUnavailable, never as an accepted or delivered +// message, so a caller cannot mistake the disabled mode for a delivery. +type Sender struct{} + +var _ outbound.MailSender = (*Sender)(nil) + +func NewSender() *Sender { + return &Sender{} +} + +// Send validates the message first so that local runs without a transport +// still expose invalid messages, then reports the channel as unavailable. It +// logs nothing and keeps no copy of the recipient or the content. +func (sender *Sender) Send(_ context.Context, mail outbound.OutgoingMail) (outbound.SendResult, error) { + if err := mail.Validate(); err != nil { + return outbound.SendResult{}, fmt.Errorf("Sender.Send - validate mail: %w", err) + } + return outbound.SendResult{}, fmt.Errorf("Sender.Send - EMAIL_PROVIDER is disabled: %w", outbound.ErrMailChannelUnavailable) +} diff --git a/backend/internal/adapter/secondary/mail/disabled/sender_test.go b/backend/internal/adapter/secondary/mail/disabled/sender_test.go new file mode 100644 index 0000000..f9d6ece --- /dev/null +++ b/backend/internal/adapter/secondary/mail/disabled/sender_test.go @@ -0,0 +1,57 @@ +package disabled_test + +import ( + "context" + "errors" + "strings" + "testing" + + "lincodex/backend/internal/adapter/secondary/mail/disabled" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const testRecipient = "candidate@example.com" + +func TestSenderReportsChannelUnavailableAndNeverAcceptance(t *testing.T) { + recipient, err := domain.NewEmailAddress(testRecipient) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + mail := outbound.OutgoingMail{ + To: recipient, + Subject: "Confirm your address", + TextBody: "verification link with raw-token-value", + IdempotencyKey: "email_verification/1", + } + canceled, cancel := context.WithCancel(context.Background()) + cancel() + + for name, ctx := range map[string]context.Context{"active context": context.Background(), "canceled context": canceled} { + t.Run(name, func(t *testing.T) { + result, err := disabled.NewSender().Send(ctx, mail) + if !errors.Is(err, outbound.ErrMailChannelUnavailable) { + t.Fatalf("Send() error = %v, want ErrMailChannelUnavailable", err) + } + // Delivery and email verification code reads Outcome and + // ProviderMessageID; neither may suggest that a provider took the + // message. + if result != (outbound.SendResult{}) || result.Outcome == outbound.MailOutcomeAccepted || result.ProviderMessageID != "" { + t.Fatalf("Send() result = %+v, want the zero result", result) + } + if strings.Contains(err.Error(), testRecipient) || strings.Contains(err.Error(), "raw-token-value") { + t.Fatalf("Send() error exposes message content: %v", err) + } + }) + } +} + +func TestSenderRejectsInvalidMailBeforeReportingUnavailability(t *testing.T) { + result, err := disabled.NewSender().Send(context.Background(), outbound.OutgoingMail{}) + if !errors.Is(err, outbound.ErrInvalidOutgoingMail) || errors.Is(err, outbound.ErrMailChannelUnavailable) { + t.Fatalf("Send() error = %v, want only ErrInvalidOutgoingMail", err) + } + if result != (outbound.SendResult{}) { + t.Fatalf("Send() result = %+v, want the zero result", result) + } +} diff --git a/backend/internal/bootstrap/app.go b/backend/internal/bootstrap/app.go index 3356404..b44e44c 100644 --- a/backend/internal/bootstrap/app.go +++ b/backend/internal/bootstrap/app.go @@ -16,6 +16,7 @@ import ( "lincodex/backend/config" "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/port/outbound" ) const ( @@ -28,6 +29,9 @@ type Application struct { apiHandler http.Handler metrics *prometheus.Metrics logger *slog.Logger + // mailSender is the transport selected by EMAIL_PROVIDER. No usecase + // sends mail yet; the delivery layer will take it from here. + mailSender outbound.MailSender } func NewApplication( @@ -35,8 +39,9 @@ func NewApplication( apiHandler http.Handler, metrics *prometheus.Metrics, logger *slog.Logger, + mailSender outbound.MailSender, ) *Application { - return &Application{config: config, apiHandler: apiHandler, metrics: metrics, logger: logger} + return &Application{config: config, apiHandler: apiHandler, metrics: metrics, logger: logger, mailSender: mailSender} } func Run() (runErr error) { @@ -69,20 +74,35 @@ func Run() (runErr error) { } func run(ctx context.Context, config config.Config, logger *slog.Logger) error { - if err := config.Validate(); err != nil { - return fmt.Errorf("bootstrap.run - validate configuration: %w", err) - } - if err := migrateDatabase(ctx, config, logger); err != nil { - return fmt.Errorf("bootstrap.run - migrate database: %w", err) - } - application, cleanup, err := initialize(ctx, config, logger) + application, cleanup, err := start(ctx, config, logger) if err != nil { - return fmt.Errorf("bootstrap.run - initialize application: %w", err) + return err } defer cleanup() return application.run(ctx) } +// start prepares the application without opening listeners. The mail +// transport is selected before migrations, so a configuration that cannot +// start never changes the database. +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) + } + mailSender, err := newMailSender(config, logger) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.start - select mail transport: %w", err) + } + if err := migrateDatabase(ctx, config, logger); err != nil { + return nil, nil, fmt.Errorf("bootstrap.start - migrate database: %w", err) + } + application, cleanup, err := initialize(ctx, config, logger, mailSender) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.start - initialize application: %w", err) + } + return application, cleanup, nil +} + func logLevel(value string) logkit.Level { switch value { case "debug": diff --git a/backend/internal/bootstrap/mail.go b/backend/internal/bootstrap/mail.go new file mode 100644 index 0000000..83c6c92 --- /dev/null +++ b/backend/internal/bootstrap/mail.go @@ -0,0 +1,48 @@ +package bootstrap + +import ( + "errors" + "fmt" + "log/slog" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/mail/disabled" + "lincodex/backend/internal/port/outbound" +) + +// errMailTransportNotBuilt reports a valid EMAIL_PROVIDER whose transport has +// no adapter in this build yet. Startup fails instead of falling back to +// another transport. +var errMailTransportNotBuilt = errors.New("mail transport is not available in this build") + +// newMailSender binds the MailSender port to the one transport that +// EMAIL_PROVIDER selects. Each provider maps to exactly one constructor, and +// a failure never falls back to another transport. A transport task replaces +// the errMailTransportNotBuilt return in its case with its constructor; until +// then resend and smtp fail startup after their settings are validated. +func newMailSender(settings config.Config, logger *slog.Logger) (outbound.MailSender, error) { + if err := settings.ValidateMail(); err != nil { + return nil, fmt.Errorf("bootstrap.newMailSender - validate mail settings: %w", err) + } + + var sender outbound.MailSender + switch settings.EmailProvider { + case config.EmailProviderDisabled: + sender = disabled.NewSender() + case config.EmailProviderResend: + return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=resend: %w", errMailTransportNotBuilt) + case config.EmailProviderSMTP: + return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=smtp: %w", errMailTransportNotBuilt) + default: + // ValidateMail rejects unknown providers; this guards a new constant + // that has no case here yet. + return nil, errors.New("bootstrap.newMailSender - EMAIL_PROVIDER has no transport") + } + + // Only the provider name is logged, never the sender, keys, or hosts. + logger.Info("mail transport selected", slog.String("email_provider", string(settings.EmailProvider))) + if settings.EmailProvider == config.EmailProviderDisabled { + logger.Warn("mail delivery is disabled; every send is reported as channel unavailable and nothing is sent") + } + return sender, nil +} diff --git a/backend/internal/bootstrap/mail_test.go b/backend/internal/bootstrap/mail_test.go new file mode 100644 index 0000000..a7f1ce6 --- /dev/null +++ b/backend/internal/bootstrap/mail_test.go @@ -0,0 +1,186 @@ +package bootstrap + +import ( + "bytes" + "errors" + "log/slog" + "strings" + "testing" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/mail/disabled" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + testSenderAddress = "no-reply@example.com" + testResendAPIKey = "re_bootstrap-test-key" + testSMTPPassword = "bootstrap-smtp-password" + // unreachableDatabaseURL fails as soon as migrations try to use it, so a + // startup error that is not a migration error proves that the mail + // transport was selected before the database was touched. + unreachableDatabaseURL = "postgres://app:db-password@db:not-a-port/app" +) + +// loadMailConfig loads the full process configuration with the given mail +// settings, as Run does from the environment. +func loadMailConfig(t *testing.T, mail map[string]string) config.Config { + t.Helper() + values := map[string]string{ + "SEAWEEDFS_ACCESS_KEY": "test-access", + "SEAWEEDFS_SECRET_KEY": "test-secret", + "EMAIL_FROM": "Lincodex <" + testSenderAddress + ">", + "APP_PUBLIC_URL": "http://localhost:8080", + // Settings of every transport are present so that each case also + // shows that only the selected transport's settings are used. + "RESEND_API_KEY": testResendAPIKey, + "SMTP_HOST": "smtp.example.com", + "SMTP_PORT": "587", + "SMTP_USERNAME": "mailer", + "SMTP_PASSWORD": testSMTPPassword, + "SMTP_TLS_MODE": "starttls", + } + for key, value := range mail { + values[key] = value + } + settings, err := config.LoadFromEnv(func(key string) (string, bool) { + value, ok := values[key] + return value, ok + }) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + return settings +} + +func captureLogs() (*slog.Logger, *bytes.Buffer) { + var logs bytes.Buffer + return slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})), &logs +} + +func assertNoMailSecrets(t *testing.T, output string) { + t.Helper() + for _, secret := range []string{testSenderAddress, testResendAPIKey, testSMTPPassword, "smtp.example.com", "db-password"} { + if strings.Contains(output, secret) { + t.Fatalf("startup output exposes a mail setting: %s", output) + } + } +} + +func TestStartWithDisabledMailSelectsTheDisabledTransport(t *testing.T) { + settings := loadMailConfig(t, map[string]string{"EMAIL_PROVIDER": "disabled"}) + logger, logs := captureLogs() + + application, cleanup, err := start(t.Context(), settings, logger) + if err != nil { + t.Fatalf("start() error = %v", err) + } + t.Cleanup(cleanup) + + if _, ok := application.mailSender.(*disabled.Sender); !ok { + t.Fatalf("mail sender = %T, want *disabled.Sender", application.mailSender) + } + recipient, err := domain.NewEmailAddress("candidate@example.com") + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + result, err := application.mailSender.Send(t.Context(), outbound.OutgoingMail{ + To: recipient, + Subject: "Confirm your address", + TextBody: "Confirm your address", + IdempotencyKey: "email_verification/harness", + }) + if !errors.Is(err, outbound.ErrMailChannelUnavailable) { + t.Fatalf("Send() error = %v, want ErrMailChannelUnavailable", err) + } + if result.Outcome == outbound.MailOutcomeAccepted || result.ProviderMessageID != "" { + t.Fatalf("Send() result = %+v, disabled mode must never report acceptance", result) + } + + output := logs.String() + if !strings.Contains(output, `msg="mail transport selected" email_provider=disabled`) { + t.Fatalf("startup did not log the selected provider: %s", output) + } + if !strings.Contains(output, "level=WARN msg=\"mail delivery is disabled") { + t.Fatalf("startup did not warn that mail is disabled: %s", output) + } + assertNoMailSecrets(t, output) +} + +func TestStartRejectsTransportsThatThisBuildDoesNotProvide(t *testing.T) { + tests := []struct { + provider string + want string + }{ + {provider: "resend", want: "bootstrap.start - select mail transport: bootstrap.newMailSender - EMAIL_PROVIDER=resend: mail transport is not available in this build"}, + {provider: "smtp", want: "bootstrap.start - select mail transport: bootstrap.newMailSender - EMAIL_PROVIDER=smtp: mail transport is not available in this build"}, + } + for _, test := range tests { + t.Run(test.provider, func(t *testing.T) { + settings := loadMailConfig(t, map[string]string{ + "EMAIL_PROVIDER": test.provider, + "DATABASE_URL": unreachableDatabaseURL, + }) + logger, logs := captureLogs() + + application, cleanup, err := start(t.Context(), settings, logger) + if err == nil { + cleanup() + t.Fatalf("start() = %v, want a startup error", application) + } + if err.Error() != test.want || !errors.Is(err, errMailTransportNotBuilt) { + t.Fatalf("start() error = %q, want %q", err, test.want) + } + if strings.Contains(logs.String(), "mail transport selected") { + t.Fatalf("startup logged a selected transport after failing: %s", logs.String()) + } + assertNoMailSecrets(t, err.Error()+logs.String()) + }) + } +} + +func TestStartRejectsInvalidMailSettingsBeforeMigrations(t *testing.T) { + valid := loadMailConfig(t, map[string]string{"EMAIL_PROVIDER": "disabled", "DATABASE_URL": unreachableDatabaseURL}) + tests := []struct { + name string + change func(*config.Config) + want string + }{ + {name: "unknown provider", change: func(settings *config.Config) { settings.EmailProvider = "sendgrid" }, want: "Config.ValidateMail - EMAIL_PROVIDER must be one of resend, smtp, or disabled"}, + {name: "missing provider", change: func(settings *config.Config) { settings.EmailProvider = "" }, want: "Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled"}, + {name: "missing sender", change: func(settings *config.Config) { settings.EmailFrom = "" }, want: "config.validateEmailFrom - EMAIL_FROM must be set"}, + {name: "plain HTTP public URL", change: func(settings *config.Config) { settings.AppPublicURL = "http://lincodex.example" }, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https; http is allowed only for localhost, 127.0.0.1, or [::1]"}, + {name: "timeout out of range", change: func(settings *config.Config) { settings.EmailTimeout = 0 }, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between 1s and 1m0s"}, + {name: "Resend without key", change: func(settings *config.Config) { settings.EmailProvider = config.EmailProviderResend }, want: "config.validateResendAPIKey - RESEND_API_KEY must be set when EMAIL_PROVIDER is resend"}, + {name: "SMTP without settings", change: func(settings *config.Config) { settings.EmailProvider = config.EmailProviderSMTP }, want: "Config.validateSMTP - SMTP_HOST must be set when EMAIL_PROVIDER is smtp"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + settings := valid + test.change(&settings) + logger, logs := captureLogs() + + _, _, err := start(t.Context(), settings, logger) + want := "bootstrap.start - validate configuration: " + test.want + if err == nil || err.Error() != want { + t.Fatalf("start() error = %v, want %q", err, want) + } + assertNoMailSecrets(t, err.Error()+logs.String()) + }) + } +} + +func TestNewMailSenderValidatesSettingsItself(t *testing.T) { + settings := loadMailConfig(t, map[string]string{"EMAIL_PROVIDER": "disabled"}) + settings.EmailFrom = "not a mailbox" + logger, logs := captureLogs() + + sender, err := newMailSender(settings, logger) + if sender != nil || err == nil || !strings.HasPrefix(err.Error(), "bootstrap.newMailSender - validate mail settings: config.validateEmailFrom - ") { + t.Fatalf("newMailSender() = (%v, %v), want a validation error", sender, err) + } + if logs.Len() != 0 { + t.Fatalf("newMailSender() logged a selection for invalid settings: %s", logs.String()) + } +} diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index 9efc53b..4f3e4aa 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -19,10 +19,18 @@ import ( redisadapter "lincodex/backend/internal/adapter/secondary/redis" "lincodex/backend/internal/adapter/secondary/seaweedfs" "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/health" ) -func initialize(ctx context.Context, config config.Config, logger *slog.Logger) (*Application, func(), error) { +// initialize receives the mail sender that start selected, so an unusable +// EMAIL_PROVIDER fails before any dependency is created. +func initialize( + ctx context.Context, + config config.Config, + logger *slog.Logger, + mailSender outbound.MailSender, +) (*Application, func(), error) { wire.Build( wire.NewSet( postgres.NewHealthChecker, diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index 5957f04..ae487f1 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -17,13 +17,16 @@ import ( "lincodex/backend/internal/adapter/secondary/redis" "lincodex/backend/internal/adapter/secondary/seaweedfs" "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/health" "log/slog" ) // Injectors from wire.go: -func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger) (*Application, func(), error) { +// initialize receives the mail sender that start selected, so an unusable +// EMAIL_PROVIDER fails before any dependency is created. +func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, mailSender outbound.MailSender) (*Application, func(), error) { healthChecker, cleanup, err := postgres.NewHealthChecker(ctx, config2) if err != nil { return nil, nil, err @@ -52,7 +55,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger) cleanup() return nil, nil, err } - application := NewApplication(config2, httpHandler, metrics, logger) + application := NewApplication(config2, httpHandler, metrics, logger, mailSender) return application, func() { cleanup3() cleanup2() diff --git a/backend/internal/port/outbound/mail.go b/backend/internal/port/outbound/mail.go new file mode 100644 index 0000000..4815430 --- /dev/null +++ b/backend/internal/port/outbound/mail.go @@ -0,0 +1,181 @@ +package outbound + +import ( + "context" + "errors" + "fmt" + "log/slog" + "strings" + "time" + + "lincodex/backend/internal/domain" +) + +const ( + // maxMailIdempotencyKeyLength follows the Resend Idempotency-Key limit of + // 256 characters; SMTP has no such key, so the strictest provider rule + // applies. + maxMailIdempotencyKeyLength = 256 + redactedOutgoingMail = "[redacted outgoing mail]" +) + +var ( + // ErrMailChannelUnavailable reports that no mail transport is active + // (EMAIL_PROVIDER=disabled). Nothing was sent and nothing was handed to a + // provider. Callers must record the message as not sent; it is never a + // delivery, and it never confirms an email address or satisfies an + // account check. + ErrMailChannelUnavailable = errors.New("mail channel unavailable") + + // ErrInvalidOutgoingMail reports a message that fails + // OutgoingMail.Validate. It is a caller bug, not a provider rejection, and + // nothing was sent. + ErrInvalidOutgoingMail = errors.New("invalid outgoing mail") +) + +// MailOutcome is what one transport attempt established about a message. The +// zero value is not an outcome and must never be read as acceptance. +type MailOutcome string + +const ( + // MailOutcomeAccepted means the provider accepted the request and returned + // a message ID. It does not mean the message was delivered or read. + MailOutcomeAccepted MailOutcome = "accepted" + + // MailOutcomeRejected means the provider answered and refused the + // request; it did not take the message. Rejection says why. + MailOutcomeRejected MailOutcome = "rejected" + + // MailOutcomeUnknown means the request may have reached the provider but + // no conclusive answer came back, for example a timeout or a connection + // lost after the request was written. The message may or may not have + // been accepted (delivery_uncertain). It is not a failure: a retry must + // reuse the same IdempotencyKey so a provider that supports keys can + // deduplicate it. + MailOutcomeUnknown MailOutcome = "unknown" +) + +// MailRejection is a provider-independent reason for MailOutcomeRejected that +// the delivery layer can map to its retry policy. It never carries provider +// text, recipients, or message content. +type MailRejection string + +const ( + // MailRejectionPermanent means the provider will not accept this message, + // for example an unverified sender domain or a suppressed recipient. + MailRejectionPermanent MailRejection = "permanent" + + // MailRejectionInvalidRequest means the provider rejected the request + // shape or credentials; retrying the same request cannot help. + MailRejectionInvalidRequest MailRejection = "invalid_request" + + // MailRejectionRateLimited means a short-term rate limit; RetryAfter may + // say when to try again. + MailRejectionRateLimited MailRejection = "rate_limited" + + // MailRejectionQuotaExhausted means a daily or monthly sending quota is + // used up; retrying before the quota resets cannot help. + MailRejectionQuotaExhausted MailRejection = "quota_exhausted" + + // MailRejectionTemporary means a transient provider-side refusal, such as + // a 5xx answer or an SMTP 4xx reply, that a later attempt may overcome. + MailRejectionTemporary MailRejection = "temporary" +) + +// OutgoingMail is one rendered message. The sender address comes from the +// transport configuration (EMAIL_FROM), so usecases and templates never choose +// or depend on it, nor on the provider. +// +// String, GoString, Format, and LogValue redact the whole message, because the +// recipient and the bodies are personal data and a body can carry a +// verification link. Read the fields directly where they are needed. +type OutgoingMail struct { + To domain.EmailAddress + Subject string + TextBody string + HTMLBody string + + // IdempotencyKey is stable for one logical delivery across every retry, + // for example "email_verification/". A transport that supports + // provider-side deduplication sends it; others ignore it. It must not + // contain personal data. + IdempotencyKey string +} + +// Validate reports a message that no transport could send. Errors wrap +// ErrInvalidOutgoingMail and name only the field, never its value. +func (mail OutgoingMail) Validate() error { + if mail.To.IsZero() { + return invalidOutgoingMail("recipient must be set") + } + if strings.TrimSpace(mail.Subject) == "" { + return invalidOutgoingMail("subject must not be empty") + } + // A control character in the subject could inject header lines. + if strings.ContainsFunc(mail.Subject, isControlCharacter) { + return invalidOutgoingMail("subject must not contain control characters") + } + if strings.TrimSpace(mail.TextBody) == "" && strings.TrimSpace(mail.HTMLBody) == "" { + return invalidOutgoingMail("text or HTML body must not be empty") + } + if length := len(mail.IdempotencyKey); length == 0 || length > maxMailIdempotencyKeyLength { + return invalidOutgoingMail("idempotency key must have 1 to 256 characters") + } + for index := range len(mail.IdempotencyKey) { + if character := mail.IdempotencyKey[index]; character <= ' ' || character > '~' { + return invalidOutgoingMail("idempotency key must contain printable ASCII characters without spaces") + } + } + return nil +} + +func (mail OutgoingMail) String() string { return redactedOutgoingMail } + +func (mail OutgoingMail) GoString() string { return redactedOutgoingMail } + +// Format redacts every verb; without it %+v would print the fields. +func (mail OutgoingMail) Format(state fmt.State, _ rune) { + _, _ = state.Write([]byte(redactedOutgoingMail)) +} + +func (mail OutgoingMail) LogValue() slog.Value { return slog.StringValue(redactedOutgoingMail) } + +func isControlCharacter(character rune) bool { + return character < ' ' || character == 0x7f +} + +func invalidOutgoingMail(reason string) error { + return fmt.Errorf("OutgoingMail.Validate - %s: %w", reason, ErrInvalidOutgoingMail) +} + +// SendResult is the outcome of one attempt that may have reached a provider. +type SendResult struct { + Outcome MailOutcome + + // ProviderMessageID is set only for MailOutcomeAccepted. + ProviderMessageID string + + // Rejection is set only for MailOutcomeRejected. + Rejection MailRejection + + // RetryAfter is the provider's requested wait for a rejected attempt, or + // zero when the provider gave none. + RetryAfter time.Duration +} + +// MailSender hands one message to the configured transport. +// +// Send makes exactly one attempt and never retries; retries, backoff, and +// deduplication belong to the delivery layer, which also records outcomes. +// A nil error comes with an Outcome of accepted, rejected, or unknown. A +// non-nil error means the message certainly did not leave the process: it +// wraps ErrMailChannelUnavailable when no transport is active, +// ErrInvalidOutgoingMail for an invalid message, or the context error when +// ctx ended before the request was sent. The returned SendResult is then +// zero and must be ignored. +// +// Errors and logs never include recipients, subjects, bodies, credentials, or +// raw provider responses. +type MailSender interface { + Send(ctx context.Context, mail OutgoingMail) (SendResult, error) +} diff --git a/backend/internal/port/outbound/mail_test.go b/backend/internal/port/outbound/mail_test.go new file mode 100644 index 0000000..9145097 --- /dev/null +++ b/backend/internal/port/outbound/mail_test.go @@ -0,0 +1,98 @@ +package outbound_test + +import ( + "bytes" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + testRecipient = "Private.Person@example.com" + testSubject = "Confirm your address" + testTextBody = "Open https://lincodex.example/verify?token=raw-token-value" + testHTMLBody = "Confirm" +) + +func validOutgoingMail(t *testing.T) outbound.OutgoingMail { + t.Helper() + recipient, err := domain.NewEmailAddress(testRecipient) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + return outbound.OutgoingMail{ + To: recipient, + Subject: testSubject, + TextBody: testTextBody, + HTMLBody: testHTMLBody, + IdempotencyKey: "email_verification/0190d3f4-0000-7000-8000-000000000001", + } +} + +func TestOutgoingMailValidateAcceptsOneBody(t *testing.T) { + textOnly := validOutgoingMail(t) + textOnly.HTMLBody = "" + htmlOnly := validOutgoingMail(t) + htmlOnly.TextBody = "" + longestKey := validOutgoingMail(t) + longestKey.IdempotencyKey = strings.Repeat("k", 256) + for name, mail := range map[string]outbound.OutgoingMail{"text only": textOnly, "HTML only": htmlOnly, "256-character key": longestKey} { + t.Run(name, func(t *testing.T) { + if err := mail.Validate(); err != nil { + t.Fatalf("Validate() error = %v", err) + } + }) + } +} + +func TestOutgoingMailValidateRejectsUnsendableMail(t *testing.T) { + tests := []struct { + name string + change func(*outbound.OutgoingMail) + }{ + {name: "missing recipient", change: func(mail *outbound.OutgoingMail) { mail.To = domain.EmailAddress{} }}, + {name: "blank subject", change: func(mail *outbound.OutgoingMail) { mail.Subject = " " }}, + {name: "subject header injection", change: func(mail *outbound.OutgoingMail) { mail.Subject = testSubject + "\r\nBcc: other@example.com" }}, + {name: "no body", change: func(mail *outbound.OutgoingMail) { mail.TextBody, mail.HTMLBody = " ", "" }}, + {name: "missing idempotency key", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = "" }}, + {name: "idempotency key too long", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = strings.Repeat("k", 257) }}, + {name: "idempotency key with space", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = "email verification" }}, + {name: "idempotency key non-ASCII", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = "письмо/1" }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + mail := validOutgoingMail(t) + test.change(&mail) + err := mail.Validate() + if !errors.Is(err, outbound.ErrInvalidOutgoingMail) { + t.Fatalf("Validate() error = %v, want ErrInvalidOutgoingMail", err) + } + if !strings.HasPrefix(err.Error(), "OutgoingMail.Validate - ") { + t.Fatalf("Validate() error = %q, want the OutgoingMail.Validate location", err) + } + for _, private := range []string{testRecipient, testSubject, "raw-token-value", "other@example.com"} { + if strings.Contains(err.Error(), private) { + t.Fatalf("Validate() error exposes message content: %v", err) + } + } + }) + } +} + +func TestOutgoingMailIsRedacted(t *testing.T) { + mail := validOutgoingMail(t) + wrapper := struct{ Mail outbound.OutgoingMail }{Mail: mail} + var logs bytes.Buffer + slog.New(slog.NewJSONHandler(&logs, nil)).Info("redaction", "mail", mail, slog.Group("nested", "mail", mail)) + formatted := fmt.Sprintf("%v %+v %#v %s %q %x %d %+v %#v", mail, mail, mail, mail, mail, mail, mail, wrapper, wrapper) + logs.String() + for _, private := range []string{"Private.Person", "private.person", testSubject, "raw-token-value", "Confirm"} { + if strings.Contains(formatted, private) { + t.Fatalf("formatted output exposes message content: %s", formatted) + } + } +} diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 96558e3..89945cf 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -187,6 +187,16 @@ services: SEAWEEDFS_REGION: us-east-1 SEAWEEDFS_TIMEOUT: 10s KAFKA_BROKERS: kafka:9092 + EMAIL_PROVIDER: ${EMAIL_PROVIDER:?Set EMAIL_PROVIDER to resend, smtp, or disabled in the root .env file} + EMAIL_FROM: ${EMAIL_FROM:?Set EMAIL_FROM in the root .env file} + EMAIL_TIMEOUT: ${EMAIL_TIMEOUT:-10s} + APP_PUBLIC_URL: ${APP_PUBLIC_URL:?Set APP_PUBLIC_URL in the root .env file} + RESEND_API_KEY: ${RESEND_API_KEY:-} + SMTP_HOST: ${SMTP_HOST:-} + SMTP_PORT: ${SMTP_PORT:-} + SMTP_USERNAME: ${SMTP_USERNAME:-} + SMTP_PASSWORD: ${SMTP_PASSWORD:-} + SMTP_TLS_MODE: ${SMTP_TLS_MODE:-} depends_on: postgres: condition: service_healthy diff --git a/deploy/scripts/smoke.sh b/deploy/scripts/smoke.sh index 093bcf4..459a17a 100644 --- a/deploy/scripts/smoke.sh +++ b/deploy/scripts/smoke.sh @@ -10,8 +10,11 @@ port=18080 network="${project}_default" started=0 +# The smoke stack sends no mail: it uses EMAIL_PROVIDER=disabled from +# .env.example and points mail links at its own loopback port. compose() { - APP_PROJECT="$project" APP_NETWORK="$app_network" APP_HTTP_PORT="$port" docker compose \ + APP_PROJECT="$project" APP_NETWORK="$app_network" APP_HTTP_PORT="$port" \ + APP_PUBLIC_URL="http://localhost:$port" docker compose \ --env-file "$env_file" \ -p "$project" \ -f "$compose_file" \ @@ -84,6 +87,11 @@ wait_for_readiness() { wait_for "http://127.0.0.1:$port/healthz" wait_for "http://127.0.0.1:$port/api/v1/healthz" +backend_logs=$(compose logs --no-color backend) +if [[ "$backend_logs" != *'mail transport selected'*'disabled'* ]]; then + printf '%s\n' 'Backend did not report EMAIL_PROVIDER=disabled at startup.' >&2 + exit 1 +fi wait_for_readiness status=$(curl --silent --show-error --output /dev/null --write-out '%{http_code}' \ "http://127.0.0.1:$port/api/v1/missing") @@ -122,4 +130,4 @@ fi curl --fail --silent --show-error "http://127.0.0.1:$port/api/v1/healthz" >/dev/null compose up -d --wait --wait-timeout 90 seaweedfs wait_for_readiness -printf '%s\n' 'Technical smoke passed: frontend, API routing, PostgreSQL, Redis, SeaweedFS, dependency recovery, and storage authentication.' +printf '%s\n' 'Technical smoke passed: frontend, API routing, PostgreSQL, Redis, SeaweedFS, dependency recovery, storage authentication, and the disabled mail transport.' diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 4800c18..a3d946c 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -77,6 +77,18 @@ The outbox uniqueness rule is a backstop, not concurrency control. Aggregate upd Planned relay contract (TASK-009): the relay selects unpublished rows (`published_at IS NULL`) ordered by `position` on every pass and never keeps an `occurred_at` or `position` watermark, because a row with a smaller position can become visible after a larger one commits. It publishes the events of one aggregate in `aggregate_version` order and then sets `published_at`. Also planned: retry bookkeeping (attempt count and last error, added by an additive migration), retention of published rows, topics, and idempotent consumers. Bootstrap does not wire the transactor yet because no product usecase uses it; the first business transaction wires it together with a shared pool. +### Mail transport + +Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: the Resend transport (`mail/resend/`, the primary provider for the working stand, TASK-013) and an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP). Until they exist, `resend` and `smtp` fail startup after their settings are validated. Settings are described in [DEPLOY.md](DEPLOY.md#mail). + +`Send(ctx, OutgoingMail)` makes exactly one attempt. `OutgoingMail` carries the recipient, subject, text and HTML bodies, and an idempotency key that stays the same for one logical delivery across retries (1 to 256 printable ASCII characters, the Resend limit, without personal data); the sender comes from `EMAIL_FROM`. With a nil error the result is one of: + +- `accepted`: the provider accepted the request and returned `ProviderMessageID`. This is not delivery or reading. +- `rejected`: the provider answered and refused; `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`, with an optional `RetryAfter`. +- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`). It is not a failure; a retry reuses the idempotency key. + +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. + ## Repository map and package purpose ```text @@ -110,7 +122,7 @@ backend/ domain/ flat package; DomainEvent, identity types usecase/health/ operational readiness usecase port/inbound/ readiness input boundary - port/outbound/ readiness, cache, object storage, transaction, outbox, and identity boundaries + port/outbound/ readiness, cache, object storage, transaction, outbox, identity, and mail boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -118,6 +130,7 @@ backend/ v1/ handwritten health endpoint router.go chi composition adapter/secondary/ + 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/sqlc/ generated SQL adapter @@ -132,9 +145,9 @@ backend/ 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`. -Product domain types and usecase modules, mail/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. +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, a Redis cache adapter, and a SeaweedFS S3 adapter. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail, 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, 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/`. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 362a094..f4acea1 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -64,6 +64,28 @@ The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` boot down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop. +## Mail + +The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects exactly one transport: `resend` (the Resend HTTP API, the primary provider for the working stand), `smtp` (a separate SMTP relay), or `disabled`. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read. + +Current state: this build contains only the `disabled` transport. With `resend` or `smtp`, the backend validates that transport's settings and then exits with `EMAIL_PROVIDER=resend: mail transport is not available in this build` (or `EMAIL_PROVIDER=smtp: ...`); under Compose, `restart: unless-stopped` restarts the container repeatedly. The Resend transport comes in a later task; SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` therefore use `disabled`. Switch the working stand to `resend` only after the build contains the Resend transport. + +`disabled` sends nothing. Every send returns `ErrMailChannelUnavailable` without a provider message ID and is never reported as accepted or delivered. It does not confirm an email address, mark an account verified, or skip an account check. The startup log contains `mail transport selected` with `email_provider` and, for `disabled`, a `mail delivery is disabled` warning. + +| Variable | Default | Validation | +| --- | --- | --- | +| `EMAIL_PROVIDER` | none, required | `resend`, `smtp`, or `disabled`, case-insensitive | +| `EMAIL_FROM` | none, required | One mailbox: `no-reply@example.com` or `Lincodex `. Printable ASCII only. The address follows the account address rules: unquoted local part and a DNS domain with at least two labels, no IP literal. | +| `EMAIL_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one transport attempt | +| `APP_PUBLIC_URL` | none, required | Public origin for links in mail: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. | +| `RESEND_API_KEY` | empty | Read only for `resend`, where it is required. Printable ASCII without whitespace. The `re_` prefix shown in Resend examples is not enforced. | +| `SMTP_HOST` | empty | Read only for `smtp`, where it is required. Hostname or IP address without a port. | +| `SMTP_PORT` | empty | Required for `smtp`. Integer from 1 to 65535. | +| `SMTP_USERNAME`, `SMTP_PASSWORD` | empty | Required for `smtp`; an anonymous relay is not supported. | +| `SMTP_TLS_MODE` | empty | Required for `smtp`. `starttls` (upgrade with STARTTLS, usually port 587) or `tls` (TLS from the start, usually port 465). Plaintext SMTP is not supported. | + +Compose passes these variables from the root `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider. + ## Separate ML Compose project ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index f90825c..ff97aa8 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -47,15 +47,16 @@ 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, and a 404 for an unknown API route; it does not start ML. +- 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. 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 a home page, 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`). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the backend has no Go Kafka client, topics, or readiness check for Kafka. - 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, 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 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 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 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 diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 03882c7..fa671be 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -40,7 +40,7 @@ Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub. -Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, and rejection of anonymous SeaweedFS bucket access. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It does not check contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application. +Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, and the backend startup log for `EMAIL_PROVIDER=disabled`. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application. ## Integration test bootstrap diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 5dce2b7..bdc3ba8 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -77,6 +77,18 @@ Usecase пишет через outbound-порты. `Transactor.WithinTransaction Запланированный контракт relay (TASK-009): на каждом проходе relay выбирает неопубликованные строки (`published_at IS NULL`) в порядке `position` и никогда не хранит watermark по `occurred_at` или `position`, потому что строка с меньшей позицией может стать видимой после фиксации строки с большей. События одного агрегата он публикует в порядке `aggregate_version` и затем заполняет `published_at`. Также запланированы учет повторов (счетчик попыток и последняя ошибка, добавятся аддитивной миграцией), хранение опубликованных строк, топики и идемпотентные потребители. Bootstrap пока не подключает transactor, потому что его не использует ни один продуктовый usecase; первая бизнес-транзакция подключит его вместе с общим пулом. +### Почтовый транспорт + +Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт Resend (`mail/resend/`, основной провайдер рабочего стенда, TASK-013) и транспорт SMTP relay (`mail/smtp/`, TASK-014, вне MVP). Пока их нет, `resend` и `smtp` после проверки своих настроек останавливают запуск. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта). + +`Send(ctx, OutgoingMail)` делает ровно одну попытку. `OutgoingMail` содержит получателя, тему, текстовое и HTML тело и ключ идемпотентности, который не меняется для одной логической доставки между повторами (от 1 до 256 печатных ASCII символов, предел Resend, без персональных данных); отправитель берется из `EMAIL_FROM`. При nil ошибке результат один из: + +- `accepted`: провайдер принял запрос и вернул `ProviderMessageID`. Это не доставка и не прочтение. +- `rejected`: провайдер ответил отказом; `Rejection` равен `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted` или `temporary`, возможно с `RetryAfter`. +- `unknown`: запрос мог дойти до провайдера, но однозначного ответа нет (`delivery_uncertain`). Это не ошибка доставки; повтор использует тот же ключ идемпотентности. + +Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения (TASK-053, TASK-054) обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера. + ## Структура репозитория и назначение пакетов ```text @@ -110,7 +122,7 @@ backend/ domain/ плоский пакет; DomainEvent, типы identity usecase/health/ operational readiness usecase port/inbound/ inbound граница readiness - port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox и identity + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity и почты adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -118,6 +130,7 @@ backend/ v1/ написанный вручную health endpoint router.go сборка chi router adapter/secondary/ + mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала ml/api/ generated client из backend/codegen/ogen-ml.yml postgres/ pool, migrator, transactor, запись outbox, репозитории identity, health check postgres/sqlc/ generated SQL adapter @@ -132,9 +145,9 @@ backend/ Доменные типы лежат непосредственно в `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`. -`domain/`, продуктовые `usecase/`, адаптеры почты и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. +`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, Redis cache adapter и S3-адаптер SeaweedFS. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, Redis cache adapter, S3-адаптер SeaweedFS и порт `MailSender` с транспортом `disabled`. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорты Resend и SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index a4b7709..f810b1f 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -66,6 +66,28 @@ Backend получает `KAFKA_BROKERS` - список адресов bootstrap down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова. +## Почта + +Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются. + +Текущее состояние: в этой сборке есть только транспорт `disabled`. С `resend` или `smtp` backend проверяет настройки этого транспорта и затем завершается с ошибкой `EMAIL_PROVIDER=resend: mail transport is not available in this build` (или `EMAIL_PROVIDER=smtp: ...`); в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. Транспорт Resend появится в следующей задаче, SMTP вне MVP. Поэтому `.env.example` и `make -C deploy smoke` используют `disabled`. Переключайте рабочий стенд на `resend` только после того, как сборка будет содержать транспорт Resend. + +`disabled` ничего не отправляет. Каждая отправка возвращает `ErrMailChannelUnavailable` без идентификатора сообщения провайдера и никогда не считается принятой или доставленной. Этот режим не подтверждает email, не отмечает аккаунт подтвержденным и не пропускает проверки аккаунта. В логе запуска есть `mail transport selected` с полем `email_provider`, а для `disabled` еще и предупреждение `mail delivery is disabled`. + +| Переменная | По умолчанию | Проверка | +| --- | --- | --- | +| `EMAIL_PROVIDER` | нет, обязательна | `resend`, `smtp` или `disabled`, без учета регистра | +| `EMAIL_FROM` | нет, обязательна | Один mailbox: `no-reply@example.com` или `Lincodex `. Только печатные ASCII символы. Адрес подчиняется правилам адресов аккаунтов: local part без кавычек и DNS-домен минимум из двух меток, без IP literal. | +| `EMAIL_TIMEOUT` | `10s` | Go duration от `1s` до `1m`; ограничивает одну попытку транспорта | +| `APP_PUBLIC_URL` | нет, обязательна | Публичный origin для ссылок в письмах: `https://host[:port]`, а `http` только для `localhost`, `127.0.0.1` или `[::1]`. Без учетных данных, пути, query и fragment; один завершающий `/` отбрасывается. | +| `RESEND_API_KEY` | пусто | Читается только для `resend` и там обязательна. Печатные ASCII символы без пробелов. Префикс `re_` из примеров Resend не проверяется. | +| `SMTP_HOST` | пусто | Читается только для `smtp` и там обязательна. Имя хоста или IP адрес без порта. | +| `SMTP_PORT` | пусто | Обязательна для `smtp`. Целое число от 1 до 65535. | +| `SMTP_USERNAME`, `SMTP_PASSWORD` | пусто | Обязательны для `smtp`; анонимный relay не поддерживается. | +| `SMTP_TLS_MODE` | пусто | Обязательна для `smtp`. `starttls` (переход на TLS через STARTTLS, обычно порт 587) или `tls` (TLS с начала соединения, обычно порт 465). SMTP без шифрования не поддерживается. | + +Compose передает эти переменные из корневого `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM` и `APP_PUBLIC_URL` обязательны, поэтому без них Compose не соберет конфигурацию проекта; перенесите блок почты из `.env.example` в существующий `.env`. Храните `RESEND_API_KEY` и `SMTP_PASSWORD` в окружении сервера или в хранилище секретов деплоя и никогда не коммитьте их. Ошибки конфигурации называют настройку, но не печатают ее значение, а лог запуска называет только выбранного провайдера. + ## Отдельный ML Compose ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему пока не требуются и здесь не запускаются. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 88a3f35..f1ff49e 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -47,15 +47,16 @@ 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 маршрута; ML он не запускает. +- Маршруты 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. 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`). - Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в backend нет Go клиента Kafka, топиков и проверки Kafka в readiness. - 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), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, 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`), другой бизнес-схемы нет; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index e1e86ea..b3c8bf2 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -40,7 +40,7 @@ make -C ml check-generated использует datamodel-code-generator --check API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub. -Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не проверяет получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения. +Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket и запись в логе запуска backend о `EMAIL_PROVIDER=disabled`. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не отправляет писем и не проверяет доставку почты, получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения. ## Bootstrap интеграционных тестов From dda3825786dca5835b9bfbb57d3ecbf457b7b24d Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 01:07:55 +0300 Subject: [PATCH 009/143] feat(identity): hash passwords with Argon2id and bounded inputs --- .env.example | 5 + backend/config/config.go | 10 + backend/config/password_hash.go | 47 ++ backend/config/password_hash_test.go | 47 ++ .../00002_create_identity_tables.sql | 2 +- backend/go.mod | 6 +- backend/integration_test/identity_test.go | 14 +- .../adapter/secondary/argon2id/hasher.go | 304 ++++++++++++ .../adapter/secondary/argon2id/hasher_test.go | 433 ++++++++++++++++++ backend/internal/domain/email_address.go | 29 +- backend/internal/domain/password.go | 96 ++++ backend/internal/domain/password_test.go | 132 ++++++ backend/internal/domain/redaction_test.go | 90 ++++ backend/internal/domain/secret_token.go | 28 +- backend/internal/domain/user.go | 16 +- backend/internal/port/outbound/password.go | 62 +++ backend/internal/usecase/identity/.gitkeep | 0 .../internal/usecase/identity/credentials.go | 39 ++ .../usecase/identity/credentials_test.go | 83 ++++ deploy/docker/docker-compose.yml | 6 + docs/en/ARCHITECTURE.md | 21 +- docs/en/DEPLOY.md | 2 + docs/en/DEVELOPMENT.md | 6 +- docs/ru/ARCHITECTURE.md | 21 +- docs/ru/DEPLOY.md | 2 + docs/ru/DEVELOPMENT.md | 6 +- 26 files changed, 1475 insertions(+), 32 deletions(-) create mode 100644 backend/config/password_hash.go create mode 100644 backend/config/password_hash_test.go create mode 100644 backend/internal/adapter/secondary/argon2id/hasher.go create mode 100644 backend/internal/adapter/secondary/argon2id/hasher_test.go create mode 100644 backend/internal/domain/password.go create mode 100644 backend/internal/domain/password_test.go create mode 100644 backend/internal/domain/redaction_test.go create mode 100644 backend/internal/port/outbound/password.go delete mode 100644 backend/internal/usecase/identity/.gitkeep create mode 100644 backend/internal/usecase/identity/credentials.go create mode 100644 backend/internal/usecase/identity/credentials_test.go diff --git a/.env.example b/.env.example index 34904f9..78c866f 100644 --- a/.env.example +++ b/.env.example @@ -40,6 +40,11 @@ SMTP_USERNAME= SMTP_PASSWORD= SMTP_TLS_MODE= +# Password hashing: Argon2id derivations that may run at once, from 1 to 4. +# Each takes 64 MiB; the backend container has 1 CPU and 768 MB of memory, so +# more than 1 only adds memory while the derivations share the CPU. +PASSWORD_HASH_CONCURRENCY=1 + # Optional PostgreSQL metrics login, created when the database volume is initialized. POSTGRES_EXPORTER_USER=metrics_reader POSTGRES_EXPORTER_PASSWORD=replace-this-metrics-password diff --git a/backend/config/config.go b/backend/config/config.go index 3230330..23fae2d 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -59,6 +59,10 @@ type Config struct { LogLevel string ReadinessTimeout time.Duration ShutdownTimeout time.Duration + + // PasswordHashConcurrency is the number of password hash derivations + // that may run at once; further logins and registrations wait. + PasswordHashConcurrency int } type LookupEnv func(string) (string, bool) @@ -93,6 +97,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { if err := config.loadMail(lookup); err != nil { return Config{}, err } + if err := config.loadPasswordHash(lookup); err != nil { + return Config{}, err + } var err error config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart) @@ -134,6 +141,9 @@ func (config Config) Validate() error { if err := config.ValidateMail(); err != nil { return err } + if err := config.ValidatePasswordHash(); err != nil { + return err + } if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil { return err } diff --git a/backend/config/password_hash.go b/backend/config/password_hash.go new file mode 100644 index 0000000..d131c68 --- /dev/null +++ b/backend/config/password_hash.go @@ -0,0 +1,47 @@ +package config + +import ( + "fmt" + "runtime" + "strconv" + "strings" +) + +const ( + // defaultPasswordHashConcurrency is the default number of Argon2id + // derivations with the current parameters (64 MiB, 4 lanes each) that may + // run at once. The default is lowered to GOMAXPROCS, which Go derives from + // the container CPU limit, because more parallel derivations than CPUs + // only share the same CPUs while holding more memory. + defaultPasswordHashConcurrency = 2 + // maxPasswordHashConcurrency keeps the hashing budget at 256 MiB, which + // fits under the 600 MiB GOMEMLIMIT of the 768 MiB backend container + // together with the rest of the process. + maxPasswordHashConcurrency = 4 +) + +// loadPasswordHash reads PASSWORD_HASH_CONCURRENCY. An unset value takes the +// smaller of the default and GOMAXPROCS; an empty or non-integer value is an +// error. +func (config *Config) loadPasswordHash(lookup LookupEnv) error { + config.PasswordHashConcurrency = min(defaultPasswordHashConcurrency, runtime.GOMAXPROCS(0)) + value, ok := lookup("PASSWORD_HASH_CONCURRENCY") + if !ok { + return nil + } + number, err := strconv.Atoi(strings.TrimSpace(value)) + if err != nil { + return fmt.Errorf("Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY must be an integer between 1 and %d", maxPasswordHashConcurrency) + } + config.PasswordHashConcurrency = number + return nil +} + +// ValidatePasswordHash checks the password hashing budget: the number of +// derivations with the current parameters that may run at once. +func (config Config) ValidatePasswordHash() error { + if config.PasswordHashConcurrency < 1 || config.PasswordHashConcurrency > maxPasswordHashConcurrency { + return fmt.Errorf("Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY must be between 1 and %d", maxPasswordHashConcurrency) + } + return nil +} diff --git a/backend/config/password_hash_test.go b/backend/config/password_hash_test.go new file mode 100644 index 0000000..ffe7179 --- /dev/null +++ b/backend/config/password_hash_test.go @@ -0,0 +1,47 @@ +package config + +import ( + "runtime" + "strings" + "testing" +) + +func TestLoadFromEnvPasswordHashConcurrency(t *testing.T) { + tests := map[string]struct { + values map[string]string + want int + }{ + "default": {values: nil, want: min(2, runtime.GOMAXPROCS(0))}, + "explicit": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": "3"}, want: 3}, + "spaces": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": " 1 "}, want: 1}, + "upper bound": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": "4"}, want: 4}, + } + for name, test := range tests { + settings, err := LoadFromEnv(testEnvironment(test.values)) + if err != nil { + t.Fatalf("LoadFromEnv(%s) error = %v", name, err) + } + if settings.PasswordHashConcurrency != test.want { + t.Fatalf("LoadFromEnv(%s) PasswordHashConcurrency = %d, want %d", name, settings.PasswordHashConcurrency, test.want) + } + } +} + +func TestLoadFromEnvRejectsPasswordHashConcurrency(t *testing.T) { + tests := map[string]struct { + value string + want string + }{ + "empty": {value: "", want: "Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY must be an integer between 1 and 4"}, + "not integer": {value: "four", want: "Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY"}, + "zero": {value: "0", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY must be between 1 and 4"}, + "negative": {value: "-1", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY"}, + "over bound": {value: "5", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY"}, + } + for name, test := range tests { + _, err := LoadFromEnv(testEnvironment(map[string]string{"PASSWORD_HASH_CONCURRENCY": test.value})) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv(%s) error = %v, want an error starting with %q", name, err, test.want) + } + } +} diff --git a/backend/db/migrations/00002_create_identity_tables.sql b/backend/db/migrations/00002_create_identity_tables.sql index 7733be4..a40df8e 100644 --- a/backend/db/migrations/00002_create_identity_tables.sql +++ b/backend/db/migrations/00002_create_identity_tables.sql @@ -49,7 +49,7 @@ CREATE TABLE users ( CONSTRAINT users_password_hash_format CHECK ( char_length(password_hash) <= 512 AND password_hash - ~ '^\$argon2id\$v=19\$m=[0-9]+,t=[0-9]+,p=[0-9]+\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$' + ~ '^\$argon2id\$v=19\$m=[1-9][0-9]{0,9},t=[1-9][0-9]{0,9},p=[1-9][0-9]{0,2}\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$' ), CONSTRAINT users_scenario_onboarding_step CHECK ( ( diff --git a/backend/go.mod b/backend/go.mod index f8da735..b80c456 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -26,6 +26,9 @@ require ( go.opentelemetry.io/otel v1.47.0 go.opentelemetry.io/otel/metric v1.47.0 go.opentelemetry.io/otel/trace v1.47.0 + golang.org/x/crypto v0.57.0 + golang.org/x/sync v0.23.0 + golang.org/x/text v0.42.0 ) require ( @@ -376,15 +379,12 @@ require ( go.uber.org/zap v1.28.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect go.yaml.in/yaml/v4 v4.0.0-rc.6 // indirect - golang.org/x/crypto v0.57.0 // indirect golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect golang.org/x/mod v0.41.0 // indirect golang.org/x/net v0.59.0 // indirect - golang.org/x/sync v0.23.0 // indirect golang.org/x/sys v0.48.0 // indirect golang.org/x/term v0.46.0 // indirect - golang.org/x/text v0.42.0 // indirect golang.org/x/tools v0.50.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260831171406-18b4a7587f8a // indirect diff --git a/backend/integration_test/identity_test.go b/backend/integration_test/identity_test.go index b75e683..5c31764 100644 --- a/backend/integration_test/identity_test.go +++ b/backend/integration_test/identity_test.go @@ -945,6 +945,17 @@ func TestIdentityRepositories(t *testing.T) { statement: `UPDATE users SET password_hash = 'correct horse battery staple' WHERE id = $1`, args: []any{user.ID}, }, + { + // The domain regex rejects zero and leading-zero parameters too. + constraint: "users_password_hash_format", + statement: `UPDATE users SET password_hash = '$argon2id$v=19$m=0,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_password_hash_format", + statement: `UPDATE users SET password_hash = '$argon2id$v=19$m=019456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA' WHERE id = $1`, + args: []any{user.ID}, + }, { // The key matches the address, so only the ASCII rule fails. constraint: "users_email_ascii", @@ -1111,7 +1122,8 @@ func assertSameUser(t *testing.T, got, want domain.User) { t.Helper() sameVerification := (got.EmailVerifiedAt == nil) == (want.EmailVerifiedAt == nil) && (got.EmailVerifiedAt == nil || got.EmailVerifiedAt.Equal(*want.EmailVerifiedAt)) - if got.ID != want.ID || got.Email != want.Email || got.PasswordHash.PHC() != want.PasswordHash.PHC() || + if got.ID != want.ID || got.Email.Address() != want.Email.Address() || got.Email.Normalized() != want.Email.Normalized() || + got.PasswordHash.PHC() != want.PasswordHash.PHC() || got.Scenario != want.Scenario || got.OnboardingStep != want.OnboardingStep || !sameVerification || got.RegistrationVersion != want.RegistrationVersion || !got.LastRegisteredAt.Equal(want.LastRegisteredAt) || got.Version != want.Version || !got.CreatedAt.Equal(want.CreatedAt) || !got.UpdatedAt.Equal(want.UpdatedAt) { diff --git a/backend/internal/adapter/secondary/argon2id/hasher.go b/backend/internal/adapter/secondary/argon2id/hasher.go new file mode 100644 index 0000000..1ff659a --- /dev/null +++ b/backend/internal/adapter/secondary/argon2id/hasher.go @@ -0,0 +1,304 @@ +// Package argon2id implements outbound.PasswordHasher with Argon2id (RFC 9106) +// from golang.org/x/crypto/argon2 and the PHC string format. +package argon2id + +import ( + "context" + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strconv" + "strings" + + "golang.org/x/crypto/argon2" + "golang.org/x/sync/semaphore" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// Parameters of new hashes: the second recommended option of RFC 9106, +// section 4 (64 MiB, 3 passes, 4 lanes). It is stronger than the OWASP +// Password Storage Cheat Sheet baseline (19 MiB, 2 passes, 1 lane). +const ( + recommendedMemoryKiB = 64 * 1024 + recommendedIterations = 3 + recommendedParallelism = 4 + // RFC 9106 recommends a 128-bit salt and a 256-bit tag. + saltBytes = 16 + keyBytes = 32 +) + +// Bounds for stored hashes. Verify recomputes a hash with the parameters +// stored in it, so a crafted or corrupted row must not be able to demand +// unbounded memory or time. They leave room to raise the current parameters +// and still verify older hashes until a login rehashes them. A stored hash +// must also fit the memory budget of the hasher (see Hasher). +const ( + maxStoredMemoryKiB = 2 * recommendedMemoryKiB + maxStoredIterations = 16 + maxStoredParallelism = 16 + // Argon2 needs at least 8 KiB per lane; x/crypto silently raises a lower + // value, which no conforming encoder writes. + minMemoryKiBPerLane = 8 + // The salt and digest minimums match domain.NewPasswordHash. + minStoredSaltBytes = 8 + maxStoredSaltBytes = 64 + minStoredKeyBytes = 16 + maxStoredKeyBytes = 64 + phcFieldCount = 6 + phcParameterCount = 3 +) + +type parameters struct { + memoryKiB uint32 + iterations uint32 + parallelism uint8 +} + +func recommendedParameters() parameters { + return parameters{ + memoryKiB: recommendedMemoryKiB, + iterations: recommendedIterations, + parallelism: recommendedParallelism, + } +} + +// Hasher is safe for concurrent use. Derivations share a memory budget of +// concurrency times the current memory parameter: each one holds its own +// memory parameter in a weighted semaphore while it runs, so at most +// concurrency current-parameter derivations run at once, and a stored hash +// with a larger memory parameter takes a larger share. Other calls wait in +// FIFO order until the budget frees up or their context ends; the queue is +// bounded only by the callers' contexts, and request rate limiting belongs +// to the HTTP layer. +type Hasher struct { + current parameters + budgetKiB int64 + memory *semaphore.Weighted + // dummy has the current parameters, a random salt, and a random digest + // that no password derives in practice. + dummy domain.PasswordHash +} + +var _ outbound.PasswordHasher = (*Hasher)(nil) + +// NewHasher returns a hasher with the RFC 9106 parameters and a memory +// budget for concurrency derivations with those parameters. +func NewHasher(concurrency int) (*Hasher, error) { + return newHasher(recommendedParameters(), concurrency) +} + +func newHasher(current parameters, concurrency int) (*Hasher, error) { + if concurrency < 1 { + return nil, errors.New("argon2id.newHasher - concurrency must be positive") + } + if violation := current.violation(); violation != "" { + return nil, errors.New("argon2id.newHasher - " + violation) + } + salt, err := randomBytes(saltBytes) + if err != nil { + return nil, fmt.Errorf("argon2id.newHasher - generate dummy salt: %w", err) + } + digest, err := randomBytes(keyBytes) + if err != nil { + return nil, fmt.Errorf("argon2id.newHasher - generate dummy digest: %w", err) + } + dummy, err := domain.NewPasswordHash(encodePHC(current, salt, digest)) + if err != nil { + return nil, fmt.Errorf("argon2id.newHasher - encode dummy hash: %w", err) + } + budgetKiB := int64(concurrency) * int64(current.memoryKiB) + return &Hasher{ + current: current, + budgetKiB: budgetKiB, + memory: semaphore.NewWeighted(budgetKiB), + dummy: dummy, + }, nil +} + +// Hash derives a 32-byte key with a fresh 16-byte salt from crypto/rand. +func (hasher *Hasher) Hash(ctx context.Context, password domain.Password) (domain.PasswordHash, error) { + if password.IsZero() { + return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - password must be built by a domain constructor: %w", domain.ErrInvalidPassword) + } + salt, err := randomBytes(saltBytes) + if err != nil { + return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - generate salt: %w", err) + } + key, err := hasher.derive(ctx, password, hasher.current, salt, keyBytes) + if err != nil { + return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - derive key: %w", err) + } + hash, err := domain.NewPasswordHash(encodePHC(hasher.current, salt, key)) + if err != nil { + return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - encode hash: %w", err) + } + return hash, nil +} + +// Verify recomputes the key with the salt, parameters, and key length stored +// in the hash and compares it in constant time. +func (hasher *Hasher) Verify(ctx context.Context, password domain.Password, stored domain.PasswordHash) (bool, error) { + if password.IsZero() { + return false, fmt.Errorf("Hasher.Verify - password must be built by a domain constructor: %w", domain.ErrInvalidPassword) + } + decoded, err := parsePHC(stored.PHC()) + if err != nil { + return false, fmt.Errorf("Hasher.Verify - parse stored hash: %w", err) + } + // The semaphore would block until the context ends on a weight above its + // size, so such a hash is refused up front. + if int64(decoded.parameters.memoryKiB) > hasher.budgetKiB { + return false, corruptHash("Hasher.Verify", "memory exceeds the hashing budget") + } + keyLength := uint32(len(decoded.key)) //nolint:gosec // parsePHC bounds the digest to 64 bytes. + key, err := hasher.derive(ctx, password, decoded.parameters, decoded.salt, keyLength) + if err != nil { + return false, fmt.Errorf("Hasher.Verify - derive key: %w", err) + } + if subtle.ConstantTimeCompare(key, decoded.key) != 1 { + return false, fmt.Errorf("Hasher.Verify - compare keys: %w", outbound.ErrPasswordMismatch) + } + needsRehash := decoded.parameters != hasher.current || len(decoded.salt) != saltBytes || len(decoded.key) != keyBytes + return needsRehash, nil +} + +// VerifyDummy runs Verify against the dummy hash, so it parses, waits for a +// slot, derives, and compares exactly as a real verification does. +func (hasher *Hasher) VerifyDummy(ctx context.Context, password domain.Password) error { + _, err := hasher.Verify(ctx, password, hasher.dummy) + if err != nil { + return fmt.Errorf("Hasher.VerifyDummy - verify dummy hash: %w", err) + } + // Unreachable in practice (a 2^-256 chance); fail closed all the same. + return fmt.Errorf("Hasher.VerifyDummy - dummy hash matched: %w", outbound.ErrPasswordMismatch) +} + +func (hasher *Hasher) derive(ctx context.Context, password domain.Password, params parameters, salt []byte, keyLength uint32) ([]byte, error) { + weight := int64(params.memoryKiB) + if err := hasher.acquire(ctx, weight); err != nil { + return nil, err + } + defer hasher.memory.Release(weight) + secret := []byte(password.Reveal()) + // Best effort: this clears only the byte copy handed to Argon2. The + // normalized string inside domain.Password cannot be wiped in Go and stays + // in memory until the garbage collector reuses it. + defer clear(secret) + return argon2.IDKey(secret, salt, params.iterations, params.memoryKiB, params.parallelism, keyLength), nil +} + +// acquire checks the context first, because Acquire may succeed on an ended +// context when the budget is free. +func (hasher *Hasher) acquire(ctx context.Context, weight int64) error { + if err := ctx.Err(); err != nil { + return fmt.Errorf("Hasher.acquire - context ended before hashing: %w", err) + } + if err := hasher.memory.Acquire(ctx, weight); err != nil { + return fmt.Errorf("Hasher.acquire - wait for hashing memory: %w", err) + } + return nil +} + +func randomBytes(size int) ([]byte, error) { + buffer := make([]byte, size) + if _, err := rand.Read(buffer); err != nil { + return nil, fmt.Errorf("argon2id.randomBytes - read random bytes: %w", err) + } + return buffer, nil +} + +// encodePHC writes $argon2id$v=19$m=,t=,p=$$ +// with unpadded standard base64, the format of the reference implementation. +func encodePHC(params parameters, salt, key []byte) string { + return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, params.memoryKiB, params.iterations, params.parallelism, + base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(key)) +} + +type decodedHash struct { + parameters parameters + salt []byte + key []byte +} + +// parsePHC accepts only what encodePHC writes: Argon2id version 19, the +// parameters in the order m, t, p as decimals without leading zeros, and +// unpadded standard base64. Every failure wraps outbound.ErrPasswordHashCorrupt, +// and through it domain.ErrInvalidPasswordHash, and never quotes the input. +func parsePHC(encoded string) (decodedHash, error) { + fields := strings.Split(encoded, "$") + if len(fields) != phcFieldCount || fields[0] != "" || fields[1] != "argon2id" { + return decodedHash{}, corruptHash("argon2id.parsePHC", "hash must be an Argon2id PHC string") + } + if fields[2] != "v="+strconv.Itoa(argon2.Version) { + return decodedHash{}, corruptHash("argon2id.parsePHC", "hash must use Argon2 version 19") + } + params, err := parseParameters(fields[3]) + if err != nil { + return decodedHash{}, err + } + salt, err := base64.RawStdEncoding.Strict().DecodeString(fields[4]) + if err != nil || len(salt) < minStoredSaltBytes || len(salt) > maxStoredSaltBytes { + return decodedHash{}, corruptHash("argon2id.parsePHC", "salt must be unpadded base64 of 8 to 64 bytes") + } + key, err := base64.RawStdEncoding.Strict().DecodeString(fields[5]) + if err != nil || len(key) < minStoredKeyBytes || len(key) > maxStoredKeyBytes { + return decodedHash{}, corruptHash("argon2id.parsePHC", "digest must be unpadded base64 of 16 to 64 bytes") + } + return decodedHash{parameters: params, salt: salt, key: key}, nil +} + +func parseParameters(field string) (parameters, error) { + values := strings.Split(field, ",") + if len(values) != phcParameterCount { + return parameters{}, corruptHash("argon2id.parseParameters", "parameters must be m, t, and p") + } + memory, memoryOK := parseParameter(values[0], "m=", 32) + iterations, iterationsOK := parseParameter(values[1], "t=", 32) + parallelism, parallelismOK := parseParameter(values[2], "p=", 8) + if !memoryOK || !iterationsOK || !parallelismOK { + return parameters{}, corruptHash("argon2id.parseParameters", "parameters must be m, t, and p as decimals without leading zeros") + } + params := parameters{ + memoryKiB: uint32(memory), //nolint:gosec // ParseUint limited the value to 32 bits. + iterations: uint32(iterations), //nolint:gosec // ParseUint limited the value to 32 bits. + parallelism: uint8(parallelism), //nolint:gosec // ParseUint limited the value to 8 bits. + } + if violation := params.violation(); violation != "" { + return parameters{}, corruptHash("argon2id.parseParameters", violation) + } + return params, nil +} + +// parseParameter reads one "" value that fits bitSize bits. +func parseParameter(value, prefix string, bitSize int) (uint64, bool) { + digits, found := strings.CutPrefix(value, prefix) + if !found || digits == "" || digits[0] == '0' { + return 0, false + } + number, err := strconv.ParseUint(digits, 10, bitSize) + return number, err == nil +} + +// violation returns the stored-hash bound that params break, or "". The +// current parameters must pass it too, so every new hash stays verifiable. +func (params parameters) violation() string { + switch { + case params.parallelism < 1 || params.parallelism > maxStoredParallelism: + return "parallelism must be between 1 and 16" + case params.iterations < 1 || params.iterations > maxStoredIterations: + return "iterations must be between 1 and 16" + case params.memoryKiB < minMemoryKiBPerLane*uint32(params.parallelism) || params.memoryKiB > maxStoredMemoryKiB: + return "memory must be between 8 KiB per lane and 128 MiB" + default: + return "" + } +} + +func corruptHash(location, reason string) error { + return fmt.Errorf("%s - %s: %w", location, reason, outbound.ErrPasswordHashCorrupt) +} diff --git a/backend/internal/adapter/secondary/argon2id/hasher_test.go b/backend/internal/adapter/secondary/argon2id/hasher_test.go new file mode 100644 index 0000000..e84f035 --- /dev/null +++ b/backend/internal/adapter/secondary/argon2id/hasher_test.go @@ -0,0 +1,433 @@ +package argon2id + +import ( + "bytes" + "context" + "encoding/base64" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const testRawPassword = "correct horse battery staple" + +// cheapParameters keep unit tests fast under the race detector. Tests that +// need the production cost use NewHasher. +var cheapParameters = parameters{memoryKiB: 64, iterations: 1, parallelism: 1} + +func newCheapHasher(t *testing.T, concurrency int) *Hasher { + t.Helper() + hasher, err := newHasher(cheapParameters, concurrency) + if err != nil { + t.Fatalf("newHasher() error = %v", err) + } + return hasher +} + +func newTestPassword(t *testing.T, raw string) domain.Password { + t.Helper() + password, err := domain.ParseLoginPassword(raw) + if err != nil { + t.Fatalf("ParseLoginPassword() error = %v", err) + } + return password +} + +// holdBudget takes the whole memory budget so that any derivation blocks, +// and returns the release function. +func holdBudget(t *testing.T, hasher *Hasher) func() { + t.Helper() + if !hasher.memory.TryAcquire(hasher.budgetKiB) { + t.Fatal("the hashing budget is already in use") + } + return func() { hasher.memory.Release(hasher.budgetKiB) } +} + +func mustPasswordHash(t *testing.T, phc string) domain.PasswordHash { + t.Helper() + hash, err := domain.NewPasswordHash(phc) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + return hash +} + +func TestNewHasherUsesTheRecommendedParameters(t *testing.T) { + hasher, err := NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + password := newTestPassword(t, testRawPassword) + hash, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + if !strings.HasPrefix(hash.PHC(), "$argon2id$v=19$m=65536,t=3,p=4$") { + t.Fatal("Hash() did not use Argon2id v19 with m=65536, t=3, p=4") + } + decoded, err := parsePHC(hash.PHC()) + if err != nil { + t.Fatalf("parsePHC(Hash()) error = %v", err) + } + if len(decoded.salt) != saltBytes || len(decoded.key) != keyBytes { + t.Fatalf("salt and key lengths = %d, %d, want %d, %d", len(decoded.salt), len(decoded.key), saltBytes, keyBytes) + } + needsRehash, err := hasher.Verify(context.Background(), password, hash) + if err != nil || needsRehash { + t.Fatalf("Verify(correct password) = %v, %v, want false, nil", needsRehash, err) + } +} + +func TestHashUsesAUniqueSaltAndBothHashesVerify(t *testing.T) { + hasher := newCheapHasher(t, 2) + password := newTestPassword(t, testRawPassword) + first, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + second, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + firstDecoded, err := parsePHC(first.PHC()) + if err != nil { + t.Fatalf("parsePHC() error = %v", err) + } + secondDecoded, err := parsePHC(second.PHC()) + if err != nil { + t.Fatalf("parsePHC() error = %v", err) + } + if bytes.Equal(firstDecoded.salt, secondDecoded.salt) || bytes.Equal(firstDecoded.key, secondDecoded.key) { + t.Fatal("two hashes of the same password share a salt or a key") + } + for _, hash := range []domain.PasswordHash{first, second} { + if needsRehash, err := hasher.Verify(context.Background(), password, hash); err != nil || needsRehash { + t.Fatalf("Verify() = %v, %v, want false, nil", needsRehash, err) + } + } +} + +func TestVerifyRejectsAWrongPassword(t *testing.T) { + hasher := newCheapHasher(t, 1) + hash, err := hasher.Hash(context.Background(), newTestPassword(t, testRawPassword)) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + for _, raw := range []string{"correct horse battery stapl", "Correct horse battery staple", "x"} { + needsRehash, err := hasher.Verify(context.Background(), newTestPassword(t, raw), hash) + if !errors.Is(err, outbound.ErrPasswordMismatch) || needsRehash { + t.Fatalf("Verify(wrong password) = %v, %v, want false, ErrPasswordMismatch", needsRehash, err) + } + if errors.Is(err, outbound.ErrPasswordHashCorrupt) { + t.Fatal("a wrong password was reported as a corrupt hash") + } + } +} + +func TestVerifyRejectsATamperedDigestAsAMismatch(t *testing.T) { + hasher := newCheapHasher(t, 1) + password := newTestPassword(t, testRawPassword) + hash, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + decoded, err := parsePHC(hash.PHC()) + if err != nil { + t.Fatalf("parsePHC() error = %v", err) + } + decoded.key[0] ^= 0x01 + tampered := mustPasswordHash(t, encodePHC(decoded.parameters, decoded.salt, decoded.key)) + if _, err := hasher.Verify(context.Background(), password, tampered); !errors.Is(err, outbound.ErrPasswordMismatch) { + t.Fatalf("Verify(tampered digest) error = %v, want ErrPasswordMismatch", err) + } +} + +func TestVerifyMatchesTheReferenceImplementation(t *testing.T) { + tests := map[string]struct { + phc string + heavy bool + }{ + // The Argon2id test of phc-winner-argon2 src/test.c (password + // "password", salt "somesalt"), the encoded form of the reference + // implementation. It takes 64 MiB. + "phc-winner-argon2 test.c": { + phc: "$argon2id$v=19$m=65536,t=2,p=1$c29tZXNhbHQ$CTFhFdXPJO1aFaMaO6Mm5c8y7cJHAph8ArZWb2GRPPc", + heavy: true, + }, + // The m=4096, t=4, p=4 entry of testVectors in + // golang.org/x/crypto/argon2/argon2_test.go, which that file states was + // generated with the phc-winner-argon2 CLI (24-byte tag), encoded here + // as PHC. + "x/crypto CLI vector": {phc: "$argon2id$v=19$m=4096,t=4,p=4$c29tZXNhbHQ$FF25czqfTuQ+3zPFCb6WuTTVBaTvszxa"}, + } + // The budget of one production derivation fits both vectors. + hasher, err := NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + for name, test := range tests { + if test.heavy && testing.Short() { + continue + } + needsRehash, err := hasher.Verify(context.Background(), newTestPassword(t, "password"), mustPasswordHash(t, test.phc)) + if err != nil { + t.Fatalf("Verify(%s) error = %v", name, err) + } + if !needsRehash { + t.Fatalf("Verify(%s) did not request a rehash for other parameters or sizes", name) + } + if _, err := hasher.Verify(context.Background(), newTestPassword(t, "passwore"), mustPasswordHash(t, test.phc)); !errors.Is(err, outbound.ErrPasswordMismatch) { + t.Fatalf("Verify(%s, wrong password) error = %v, want ErrPasswordMismatch", name, err) + } + } +} + +func TestVerifyReportsRehashForOtherParameters(t *testing.T) { + password := newTestPassword(t, testRawPassword) + older := newCheapHasher(t, 1) + hash, err := older.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + stronger, err := newHasher(parameters{memoryKiB: 128, iterations: 2, parallelism: 1}, 1) + if err != nil { + t.Fatalf("newHasher() error = %v", err) + } + needsRehash, err := stronger.Verify(context.Background(), password, hash) + if err != nil || !needsRehash { + t.Fatalf("Verify(older parameters) = %v, %v, want true, nil", needsRehash, err) + } +} + +func TestVerifyRejectsCorruptHashesWithoutDerivation(t *testing.T) { + salt := base64.RawStdEncoding.EncodeToString([]byte("saltsaltsaltsalt")) + digest := base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{7}, keyBytes)) + // Each value passes domain.NewPasswordHash, so only the hasher's bounds + // stop it. + tests := map[string]string{ + "huge memory": "$argon2id$v=19$m=4294967295,t=1,p=1$" + salt + "$" + digest, + "memory over 128 MiB": "$argon2id$v=19$m=131073,t=1,p=1$" + salt + "$" + digest, + "memory over the budget": "$argon2id$v=19$m=128,t=1,p=1$" + salt + "$" + digest, + "memory below 8 KiB/lane": "$argon2id$v=19$m=31,t=1,p=4$" + salt + "$" + digest, + "memory over uint32": "$argon2id$v=19$m=4294967296,t=1,p=1$" + salt + "$" + digest, + "huge iterations": "$argon2id$v=19$m=64,t=4294967295,p=1$" + salt + "$" + digest, + "iterations over 16": "$argon2id$v=19$m=64,t=17,p=1$" + salt + "$" + digest, + "parallelism over 16": "$argon2id$v=19$m=256,t=1,p=17$" + salt + "$" + digest, + "parallelism over uint8": "$argon2id$v=19$m=4096,t=1,p=256$" + salt + "$" + digest, + "salt over 64 bytes": "$argon2id$v=19$m=64,t=1,p=1$" + base64.RawStdEncoding.EncodeToString(make([]byte, 65)) + "$" + digest, + "digest over 64 bytes": "$argon2id$v=19$m=64,t=1,p=1$" + salt + "$" + base64.RawStdEncoding.EncodeToString(make([]byte, 65)), + } + // The budget is already taken: a derivation would block until the context + // ends, so a quick ErrPasswordHashCorrupt proves none started. The budget + // of one cheap derivation is 64 KiB. + hasher := newCheapHasher(t, 1) + defer holdBudget(t, hasher)() + password := newTestPassword(t, testRawPassword) + for name, phc := range tests { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + needsRehash, err := hasher.Verify(ctx, password, mustPasswordHash(t, phc)) + cancel() + if !errors.Is(err, outbound.ErrPasswordHashCorrupt) || needsRehash { + t.Fatalf("Verify(%s) = %v, %v, want false, ErrPasswordHashCorrupt", name, needsRehash, err) + } + if errors.Is(err, outbound.ErrPasswordMismatch) { + t.Fatalf("Verify(%s) reported a corrupt hash as a wrong password", name) + } + if !errors.Is(err, domain.ErrInvalidPasswordHash) { + t.Fatalf("Verify(%s) error = %v, want it to match domain.ErrInvalidPasswordHash too", name, err) + } + } + if _, err := hasher.Verify(context.Background(), password, domain.PasswordHash{}); !errors.Is(err, outbound.ErrPasswordHashCorrupt) { + t.Fatalf("Verify(zero hash) error = %v, want ErrPasswordHashCorrupt", err) + } +} + +func TestParsePHCAcceptsOnlyTheCanonicalForm(t *testing.T) { + salt := base64.RawStdEncoding.EncodeToString([]byte("saltsaltsaltsalt")) + digest := base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{7}, keyBytes)) + valid := "$argon2id$v=19$m=64,t=1,p=1$" + salt + "$" + digest + if _, err := parsePHC(valid); err != nil { + t.Fatalf("parsePHC(valid) error = %v", err) + } + for name, phc := range map[string]string{ + "empty": "", + "argon2i": strings.Replace(valid, "argon2id", "argon2i", 1), + "version 16": strings.Replace(valid, "v=19", "v=16", 1), + "missing version": strings.Replace(valid, "$v=19", "", 1), + "reordered": strings.Replace(valid, "m=64,t=1,p=1", "t=1,m=64,p=1", 1), + "leading zero": strings.Replace(valid, "m=64", "m=064", 1), + "zero iterations": strings.Replace(valid, "t=1", "t=0", 1), + "signed value": strings.Replace(valid, "t=1", "t=+1", 1), + "extra parameter": strings.Replace(valid, "p=1", "p=1,k=1", 1), + "data parameter": strings.Replace(valid, "p=1", "p=1$data=abc", 1), + "padded salt": strings.Replace(valid, salt, salt+"==", 1), + "url-safe digest": strings.Replace(valid, digest, strings.ReplaceAll(digest, "B", "-"), 1), + "short salt": strings.Replace(valid, salt, "c2FsdA", 1), + "short digest": strings.Replace(valid, digest, "aGFzaA", 1), + "trailing separator": valid + "$", + "missing leading sep": strings.TrimPrefix(valid, "$"), + } { + if _, err := parsePHC(phc); !errors.Is(err, outbound.ErrPasswordHashCorrupt) { + t.Fatalf("parsePHC(%s) error = %v, want ErrPasswordHashCorrupt", name, err) + } + } +} + +func TestVerifyDummyDoesTheSameWorkAndNeverMatches(t *testing.T) { + hasher := newCheapHasher(t, 1) + dummy, err := parsePHC(hasher.dummy.PHC()) + if err != nil { + t.Fatalf("parsePHC(dummy) error = %v", err) + } + if dummy.parameters != hasher.current || len(dummy.salt) != saltBytes || len(dummy.key) != keyBytes { + t.Fatal("the dummy hash does not use the current parameters and sizes") + } + other := newCheapHasher(t, 1) + if hasher.dummy.PHC() == other.dummy.PHC() { + t.Fatal("two hashers share a dummy hash") + } + err = hasher.VerifyDummy(context.Background(), newTestPassword(t, testRawPassword)) + if !errors.Is(err, outbound.ErrPasswordMismatch) { + t.Fatalf("VerifyDummy() error = %v, want ErrPasswordMismatch", err) + } + + // VerifyDummy waits for hashing memory like Verify does. + defer holdBudget(t, hasher)() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + if err := hasher.VerifyDummy(ctx, newTestPassword(t, testRawPassword)); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("VerifyDummy(no free slot) error = %v, want DeadlineExceeded", err) + } +} + +func TestHashingWaitsForItsShareOfTheMemoryBudget(t *testing.T) { + // Budget for two current-parameter derivations. + hasher := newCheapHasher(t, 2) + password := newTestPassword(t, testRawPassword) + hash, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + // A stored hash with twice the current memory needs the whole budget. + double, err := newHasher(parameters{memoryKiB: 2 * cheapParameters.memoryKiB, iterations: 1, parallelism: 1}, 1) + if err != nil { + t.Fatalf("newHasher() error = %v", err) + } + doubleHash, err := double.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + + // One share taken: a current derivation still runs, a double one waits. + share := int64(cheapParameters.memoryKiB) + if !hasher.memory.TryAcquire(share) { + t.Fatal("the hashing budget is already in use") + } + if _, err := hasher.Verify(context.Background(), password, hash); err != nil { + t.Fatalf("Verify(one free share) error = %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + if _, err := hasher.Verify(ctx, password, doubleHash); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Verify(double memory, one free share) error = %v, want DeadlineExceeded", err) + } + hasher.memory.Release(share) + if needsRehash, err := hasher.Verify(context.Background(), password, doubleHash); err != nil || !needsRehash { + t.Fatalf("Verify(double memory, free budget) = %v, %v, want true, nil", needsRehash, err) + } + + // The whole budget taken: every call waits until its context ends. + release := holdBudget(t, hasher) + if _, err := hasher.Hash(ctx, password); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Hash(no free memory) error = %v, want DeadlineExceeded", err) + } + if _, err := hasher.Verify(ctx, password, hash); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Verify(no free memory) error = %v, want DeadlineExceeded", err) + } + release() + + canceled, cancelNow := context.WithCancel(context.Background()) + cancelNow() + if _, err := hasher.Hash(canceled, password); !errors.Is(err, context.Canceled) { + t.Fatalf("Hash(canceled context) error = %v, want Canceled even with free memory", err) + } + // Failed and finished calls returned their share. + holdBudget(t, hasher)() +} + +func TestHasherRejectsAZeroPasswordAndInvalidSettings(t *testing.T) { + hasher := newCheapHasher(t, 1) + hash, err := hasher.Hash(context.Background(), newTestPassword(t, testRawPassword)) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + if _, err := hasher.Hash(context.Background(), domain.Password{}); !errors.Is(err, domain.ErrInvalidPassword) { + t.Fatalf("Hash(zero password) error = %v, want ErrInvalidPassword", err) + } + if _, err := hasher.Verify(context.Background(), domain.Password{}, hash); !errors.Is(err, domain.ErrInvalidPassword) { + t.Fatalf("Verify(zero password) error = %v, want ErrInvalidPassword", err) + } + if err := hasher.VerifyDummy(context.Background(), domain.Password{}); !errors.Is(err, domain.ErrInvalidPassword) { + t.Fatalf("VerifyDummy(zero password) error = %v, want ErrInvalidPassword", err) + } + for _, concurrency := range []int{0, -1} { + if _, err := NewHasher(concurrency); err == nil { + t.Fatalf("NewHasher(%d) error = nil, want an error", concurrency) + } + } + if _, err := newHasher(parameters{memoryKiB: 8, iterations: 1, parallelism: 4}, 1); err == nil { + t.Fatal("newHasher(memory below 8 KiB per lane) error = nil, want an error") + } +} + +func TestErrorsAndLogsNeverContainThePasswordOrTheHash(t *testing.T) { + hasher := newCheapHasher(t, 1) + password := newTestPassword(t, testRawPassword) + hash, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + _, mismatch := hasher.Verify(context.Background(), newTestPassword(t, "wrong password value"), hash) + corruptPHC := "$argon2id$v=19$m=131073,t=1,p=1$c2FsdHNhbHRzYWx0c2FsdA$" + base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{7}, keyBytes)) + _, corrupt := hasher.Verify(context.Background(), password, mustPasswordHash(t, corruptPHC)) + dummy := hasher.VerifyDummy(context.Background(), password) + + var logs bytes.Buffer + logger := slog.New(slog.NewJSONHandler(&logs, nil)) + for _, err := range []error{mismatch, corrupt, dummy} { + if err == nil { + t.Fatal("expected an error") + } + logger.Error("password check failed", "error", err, "password", password, "hash", hash) + } + output := logs.String() + fmt.Sprint(mismatch, corrupt, dummy) + for _, secret := range []string{testRawPassword, "wrong password value", hash.PHC(), corruptPHC, hasher.dummy.PHC()} { + if strings.Contains(output, secret) { + t.Fatalf("errors or logs expose a secret: %s", output) + } + } +} + +// BenchmarkHashRecommendedParameters measures one Hash with the production +// parameters: go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/ +func BenchmarkHashRecommendedParameters(b *testing.B) { + hasher, err := NewHasher(1) + if err != nil { + b.Fatalf("NewHasher() error = %v", err) + } + password, err := domain.NewPassword(testRawPassword) + if err != nil { + b.Fatalf("NewPassword() error = %v", err) + } + for b.Loop() { + if _, err := hasher.Hash(context.Background(), password); err != nil { + b.Fatalf("Hash() error = %v", err) + } + } +} diff --git a/backend/internal/domain/email_address.go b/backend/internal/domain/email_address.go index 1bc5274..9b553a5 100644 --- a/backend/internal/domain/email_address.go +++ b/backend/internal/domain/email_address.go @@ -38,8 +38,15 @@ var ErrInvalidEmailAddress = errors.New("invalid email address") // the domain, a rule for Unicode local parts, and SMTPUTF8 delivery. // // String, GoString, Format, and LogValue redact the address so it does not -// reach logs by accident; Address returns the real value. +// reach logs by accident; Address returns the real value. Both forms sit +// behind a pointer: fmt cannot call Format on an unexported field of an +// enclosing struct and prints its contents instead, but for a pointer it +// prints only the address. A nil pointer is the zero, invalid value. type EmailAddress struct { + value *emailAddressValue +} + +type emailAddressValue struct { address string normalized string } @@ -69,7 +76,7 @@ func NewEmailAddress(raw string) (EmailAddress, error) { if err := validateEmailDomain(domainPart); err != nil { return EmailAddress{}, err } - return EmailAddress{address: address, normalized: normalizeEmailKey(address)}, nil + return EmailAddress{value: &emailAddressValue{address: address, normalized: normalizeEmailKey(address)}}, nil } // RestoreEmailAddress rebuilds an EmailAddress from storage. It checks only @@ -79,7 +86,7 @@ func RestoreEmailAddress(address, normalized string) (EmailAddress, error) { if address == "" || normalized != normalizeEmailKey(address) { return EmailAddress{}, fmt.Errorf("domain.RestoreEmailAddress - stored key does not match the stored address: %w", ErrInvalidEmailAddress) } - return EmailAddress{address: address, normalized: normalized}, nil + return EmailAddress{value: &emailAddressValue{address: address, normalized: normalized}}, nil } // normalizeEmailKey lowercases A-Z only, independent of locale and Unicode @@ -139,13 +146,23 @@ func invalidEmailAddress(reason string) error { // Address returns the delivery form. Use it only where the address is needed: // storage, mail delivery, and the account view. -func (email EmailAddress) Address() string { return email.address } +func (email EmailAddress) Address() string { + if email.value == nil { + return "" + } + return email.value.address +} // Normalized returns the comparison key that storage keeps unique. -func (email EmailAddress) Normalized() string { return email.normalized } +func (email EmailAddress) Normalized() string { + if email.value == nil { + return "" + } + return email.value.normalized +} // IsZero reports an EmailAddress not built by NewEmailAddress. -func (email EmailAddress) IsZero() bool { return email.normalized == "" } +func (email EmailAddress) IsZero() bool { return email.value == nil } func (email EmailAddress) String() string { return redactedEmailAddress } diff --git a/backend/internal/domain/password.go b/backend/internal/domain/password.go new file mode 100644 index 0000000..e3cbce8 --- /dev/null +++ b/backend/internal/domain/password.go @@ -0,0 +1,96 @@ +package domain + +import ( + "errors" + "fmt" + "log/slog" + "unicode/utf8" + + "golang.org/x/text/unicode/norm" +) + +const ( + // MinNewPasswordCodePoints follows NIST SP 800-63B-4 for a password used + // as the only authentication factor (the NewPassword contract schema). + MinNewPasswordCodePoints = 15 + // MaxPasswordCodePoints bounds the hashing input of new and login + // passwords (NewPassword and LoginPassword in the contract). + MaxPasswordCodePoints = 128 + // minLoginPasswordCodePoints only rejects an empty login password; login + // applies no registration policy, so a policy change locks nobody out. + minLoginPasswordCodePoints = 1 + // maxPasswordInputBytes caps the raw input before NFKC normalization so + // an oversized value never reaches the normalizer. 128 code points take at + // most 4 bytes each in UTF-8, so every value that the contract schema + // accepts fits. + maxPasswordInputBytes = MaxPasswordCodePoints * utf8.UTFMax +) + +// ErrInvalidPassword reports a password outside the length rules. Errors that +// wrap it name the rule, never the value or its length. +var ErrInvalidPassword = errors.New("invalid password") + +// Password is a plaintext password normalized to Unicode NFKC, as NIST SP +// 800-63B-4 recommends, so that equivalent input from different keyboards +// and platforms hashes the same. It exists only between the request and the +// password hasher and is never stored. String, GoString, Format, LogValue, +// and MarshalJSON redact it; Reveal returns the value for the hasher. The +// value sits behind a pointer so that printing an enclosing struct shows only +// an address (see redactedValue). +type Password struct { + value *string +} + +// NewPassword applies the registration policy: 15 to 128 Unicode code points +// after NFKC normalization. The blocklist of common or breached passwords is +// a separate check. +func NewPassword(raw string) (Password, error) { + return parsePassword("domain.NewPassword", raw, MinNewPasswordCodePoints) +} + +// ParseLoginPassword accepts a password entered at login: 1 to 128 Unicode +// code points after NFKC normalization. +func ParseLoginPassword(raw string) (Password, error) { + return parsePassword("domain.ParseLoginPassword", raw, minLoginPasswordCodePoints) +} + +// parsePassword runs only cheap checks, so a caller can reject a value before +// any expensive hashing. The raw byte cap comes first, then UTF-8 validity, +// then normalization and the code point count. +func parsePassword(location, raw string, minCodePoints int) (Password, error) { + if len(raw) > maxPasswordInputBytes { + return Password{}, fmt.Errorf("%s - password must have at most %d bytes before normalization: %w", + location, maxPasswordInputBytes, ErrInvalidPassword) + } + if !utf8.ValidString(raw) { + return Password{}, fmt.Errorf("%s - password must be valid UTF-8: %w", location, ErrInvalidPassword) + } + normalized := norm.NFKC.String(raw) + if count := utf8.RuneCountInString(normalized); count < minCodePoints || count > MaxPasswordCodePoints { + return Password{}, fmt.Errorf("%s - password must have %d to %d code points after NFKC normalization: %w", + location, minCodePoints, MaxPasswordCodePoints, ErrInvalidPassword) + } + return Password{value: newRedactedValue(normalized)}, nil +} + +// Reveal returns the normalized password for the password hasher. Never +// store, log, or return it. +func (password Password) Reveal() string { return redactedValue(password.value) } + +// IsZero reports a Password not built by NewPassword or ParseLoginPassword. +func (password Password) IsZero() bool { return password.value == nil } + +func (password Password) String() string { return redactedSecret } + +func (password Password) GoString() string { return redactedSecret } + +func (password Password) LogValue() slog.Value { return slog.StringValue(redactedSecret) } + +// Format redacts every verb; without it %d would print the struct fields. +func (password Password) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } + +// MarshalJSON redacts the value in any JSON output, including a struct that +// embeds a Password. +func (password Password) MarshalJSON() ([]byte, error) { return redactedSecretJSON(), nil } + +func redactedSecretJSON() []byte { return []byte(`"` + redactedSecret + `"`) } diff --git a/backend/internal/domain/password_test.go b/backend/internal/domain/password_test.go new file mode 100644 index 0000000..7fec25d --- /dev/null +++ b/backend/internal/domain/password_test.go @@ -0,0 +1,132 @@ +package domain + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strings" + "testing" +) + +func TestNewPasswordCountsCodePointsAfterNFKC(t *testing.T) { + tests := map[string]struct { + raw string + want string + }{ + "15 ASCII characters": {raw: strings.Repeat("a", 15), want: strings.Repeat("a", 15)}, + "128 ASCII characters": {raw: strings.Repeat("a", 128), want: strings.Repeat("a", 128)}, + // 15 code points in 30 bytes: the limit counts code points, not bytes. + "15 Cyrillic letters": {raw: strings.Repeat("ж", 15), want: strings.Repeat("ж", 15)}, + // 128 code points in 512 bytes: the largest input the byte cap allows. + "128 four-byte characters": {raw: strings.Repeat("\U0001F600", 128), want: strings.Repeat("\U0001F600", 128)}, + // Fullwidth forms normalize to ASCII. + "fullwidth letters": {raw: strings.Repeat("pass", 4), want: strings.Repeat("pass", 4)}, + // 14 raw code points become 15 after NFKC expands the ligature. + "expanding ligature": {raw: strings.Repeat("a", 13) + "fi", want: strings.Repeat("a", 13) + "fi"}, + // Spaces and surrounding whitespace are part of the password. + "spaces kept": {raw: " correct horse battery ", want: " correct horse battery "}, + } + for name, test := range tests { + password, err := NewPassword(test.raw) + if err != nil { + t.Fatalf("NewPassword(%s) error = %v", name, err) + } + if password.Reveal() != test.want { + t.Fatalf("NewPassword(%s) did not normalize to the expected NFKC form", name) + } + } +} + +func TestNewPasswordRejectsValuesOutsideThePolicy(t *testing.T) { + tests := map[string]string{ + "empty": "", + "14 ASCII characters": strings.Repeat("a", 14), + "129 ASCII characters": strings.Repeat("a", 129), + "over the byte cap": strings.Repeat("a", maxPasswordInputBytes+1), + "129 four-byte runes": strings.Repeat("\U0001F600", 129), + "one megabyte": strings.Repeat("a", 1<<20), + "invalid UTF-8": strings.Repeat("a", 20) + "\xff", + "truncated UTF-8": strings.Repeat("a", 20) + "\xe2\x82", + "expands past the limit": strings.Repeat("fi", 65), + // 16 raw code points compose into 8 after NFKC. + "composes below the minimum": strings.Repeat("é", 8), + } + for name, raw := range tests { + _, err := NewPassword(raw) + if !errors.Is(err, ErrInvalidPassword) { + t.Fatalf("NewPassword(%s) error = %v, want ErrInvalidPassword", name, err) + } + if raw != "" && strings.Contains(err.Error(), raw) { + t.Fatalf("NewPassword(%s) error exposes the input", name) + } + } +} + +func TestNewPasswordChecksTheByteCapBeforeNormalizing(t *testing.T) { + // Valid UTF-8 would normalize; the byte cap must answer first. + _, err := NewPassword(strings.Repeat("fi", maxPasswordInputBytes)) + if !errors.Is(err, ErrInvalidPassword) || !strings.Contains(err.Error(), "bytes before normalization") { + t.Fatalf("NewPassword(oversized) error = %v, want the byte cap", err) + } +} + +func TestParseLoginPasswordAppliesOnlyTheHashingBound(t *testing.T) { + for _, raw := range []string{"a", "short", strings.Repeat("a", 128)} { + if _, err := ParseLoginPassword(raw); err != nil { + t.Fatalf("ParseLoginPassword(%d bytes) error = %v", len(raw), err) + } + } + for _, raw := range []string{"", strings.Repeat("a", 129), strings.Repeat("a", maxPasswordInputBytes+1), "\xff"} { + if _, err := ParseLoginPassword(raw); !errors.Is(err, ErrInvalidPassword) { + t.Fatalf("ParseLoginPassword(%d bytes) error = %v, want ErrInvalidPassword", len(raw), err) + } + } +} + +func TestNewPasswordAndLoginPasswordNormalizeAlike(t *testing.T) { + registered, err := NewPassword("correct horse battery") + if err != nil { + t.Fatalf("NewPassword() error = %v", err) + } + login, err := ParseLoginPassword("correct horse battery") + if err != nil { + t.Fatalf("ParseLoginPassword() error = %v", err) + } + if registered.Reveal() != login.Reveal() { + t.Fatal("equivalent registration and login input normalized differently") + } + if !(Password{}).IsZero() || registered.IsZero() { + t.Fatal("IsZero() does not distinguish a built password from the zero value") + } +} + +func TestPasswordAndPasswordHashAreRedacted(t *testing.T) { + const raw = "correct horse battery staple" + password, err := NewPassword(raw) + if err != nil { + t.Fatalf("NewPassword() error = %v", err) + } + passwordHash, err := NewPasswordHash(testPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + var logs bytes.Buffer + slog.New(slog.NewTextHandler(&logs, nil)).Info("redaction", "password", password, "hash", passwordHash) + slog.New(slog.NewJSONHandler(&logs, nil)).Info("redaction", "password", password, "hash", passwordHash) + encoded, err := json.Marshal(map[string]any{"password": password, "hash": passwordHash}) + if err != nil { + t.Fatalf("json.Marshal() error = %v", err) + } + formatted := fmt.Sprintf("%v %+v %#v %s %q %d", password, password, password, password, password, password) + + logs.String() + string(encoded) + for _, secret := range []string{raw, testPasswordHash, "c2FsdHNhbHRzYWx0"} { + if strings.Contains(formatted, secret) { + t.Fatalf("formatted output exposes a secret: %s", formatted) + } + } + if !strings.Contains(string(encoded), redactedSecret) { + t.Fatalf("json.Marshal() = %s, want redacted values", encoded) + } +} diff --git a/backend/internal/domain/redaction_test.go b/backend/internal/domain/redaction_test.go new file mode 100644 index 0000000..5820bc3 --- /dev/null +++ b/backend/internal/domain/redaction_test.go @@ -0,0 +1,90 @@ +package domain + +import ( + "bytes" + "encoding/json" + "fmt" + "log/slog" + "strings" + "testing" +) + +// nestedSecrets holds every secret type in unexported fields, where fmt does +// not call their Format, String, or GoString methods. +type nestedSecrets struct { + password Password + hash PasswordHash + token SecretToken + email EmailAddress +} + +// exportedSecrets is the same with exported fields, as in domain.User. +type exportedSecrets struct { + Password Password `json:"password"` + Hash PasswordHash `json:"hash"` + Token SecretToken `json:"token"` + Email EmailAddress `json:"email"` +} + +func TestSecretsAreRedactedInsideEnclosingStructs(t *testing.T) { + const rawPassword = "correct horse battery staple" + const rawEmail = "Secret.Person@Example.com" + password, err := NewPassword(rawPassword) + if err != nil { + t.Fatalf("NewPassword() error = %v", err) + } + hash, err := NewPasswordHash(testPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + token, err := NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + email, err := NewEmailAddress(rawEmail) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + nested := nestedSecrets{password: password, hash: hash, token: token, email: email} + exported := exportedSecrets{Password: password, Hash: hash, Token: token, Email: email} + pointer := &nested + + var logs bytes.Buffer + for _, logger := range []*slog.Logger{ + slog.New(slog.NewTextHandler(&logs, nil)), + slog.New(slog.NewJSONHandler(&logs, nil)), + } { + logger.Info("nested", "unexported", nested, "exported", exported, "pointer", pointer) + } + encoded, err := json.Marshal(exported) + if err != nil { + t.Fatalf("json.Marshal() error = %v", err) + } + output := fmt.Sprintf("%v %+v %#v %v %+v %#v %v %+v %v", + nested, nested, nested, exported, exported, exported, pointer, []nestedSecrets{nested}, map[string]nestedSecrets{"k": nested}) + + logs.String() + string(encoded) + + secrets := []string{ + rawPassword, testPasswordHash, "c2FsdHNhbHRzYWx0", token.Reveal(), rawEmail, strings.ToLower(rawEmail), + } + for _, secret := range secrets { + if strings.Contains(output, secret) { + t.Fatalf("printing an enclosing struct exposes a secret: %s", output) + } + } +} + +func TestZeroSecretValuesAreEmptyAndInvalid(t *testing.T) { + if !(Password{}).IsZero() || (Password{}).Reveal() != "" { + t.Fatal("zero Password is not empty and zero") + } + if !(PasswordHash{}).IsZero() || (PasswordHash{}).PHC() != "" { + t.Fatal("zero PasswordHash is not empty and zero") + } + if !(SecretToken{}).IsZero() || (SecretToken{}).Reveal() != "" { + t.Fatal("zero SecretToken is not empty and zero") + } + if !(EmailAddress{}).IsZero() || (EmailAddress{}).Address() != "" || (EmailAddress{}).Normalized() != "" { + t.Fatal("zero EmailAddress is not empty and zero") + } +} diff --git a/backend/internal/domain/secret_token.go b/backend/internal/domain/secret_token.go index 56d498a..0ad7e5e 100644 --- a/backend/internal/domain/secret_token.go +++ b/backend/internal/domain/secret_token.go @@ -31,8 +31,10 @@ var ( // session cookie value. Only the holder sees the raw value; storage keeps // SecretTokenHash. String and LogValue redact the value so it does not reach // logs by accident; Reveal returns it for the one place that must send it. +// The value sits behind a pointer so that printing an enclosing struct shows +// only an address (see redactedValue). type SecretToken struct { - value string + value *string } // NewSecretToken returns a token with 256 bits from crypto/rand. @@ -41,7 +43,7 @@ func NewSecretToken() (SecretToken, error) { if _, err := rand.Read(entropy); err != nil { return SecretToken{}, fmt.Errorf("domain.NewSecretToken - read random bytes: %w", err) } - return SecretToken{value: base64.RawURLEncoding.EncodeToString(entropy)}, nil + return SecretToken{value: newRedactedValue(base64.RawURLEncoding.EncodeToString(entropy))}, nil } // ParseSecretToken accepts a raw token from a request. It checks only the @@ -50,19 +52,19 @@ func ParseSecretToken(raw string) (SecretToken, error) { if !secretTokenPattern.MatchString(raw) { return SecretToken{}, fmt.Errorf("domain.ParseSecretToken - token must have 32 to 128 base64url characters: %w", ErrInvalidSecretToken) } - return SecretToken{value: raw}, nil + return SecretToken{value: newRedactedValue(raw)}, nil } // Hash returns the SHA-256 digest that storage keeps. A token carries 256 bits // of entropy, so a fast unsalted digest cannot be reversed by guessing, unlike // a password, and lookups by digest stay a single index probe. func (token SecretToken) Hash() SecretTokenHash { - return SecretTokenHash(sha256.Sum256([]byte(token.value))) + return SecretTokenHash(sha256.Sum256([]byte(token.Reveal()))) } // Reveal returns the raw value for delivery to its holder: the email link or // the Set-Cookie header. Never store or log it. -func (token SecretToken) Reveal() string { return token.value } +func (token SecretToken) Reveal() string { return redactedValue(token.value) } func (token SecretToken) String() string { return redactedSecret } @@ -73,12 +75,26 @@ func (token SecretToken) LogValue() slog.Value { return slog.StringValue(redacte // Format redacts every verb; without it %d would print the struct fields. func (token SecretToken) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } +// newRedactedValue and redactedValue hold a secret string behind a pointer. +// fmt calls Format, String, or GoString only on values it can reach through +// an interface; for an unexported field of an enclosing struct it prints the +// fields with reflection instead. A pointer field is then printed as an +// address, so the secret never appears. A nil pointer is the zero value. +func newRedactedValue(value string) *string { return &value } + +func redactedValue(value *string) string { + if value == nil { + return "" + } + return *value +} + func writeRedacted(state fmt.State, placeholder string) { _, _ = state.Write([]byte(placeholder)) } // IsZero reports a SecretToken not built by NewSecretToken or ParseSecretToken. -func (token SecretToken) IsZero() bool { return token.value == "" } +func (token SecretToken) IsZero() bool { return token.value == nil } // SecretTokenHash is the SHA-256 digest of a SecretToken. type SecretTokenHash [SecretTokenHashSize]byte diff --git a/backend/internal/domain/user.go b/backend/internal/domain/user.go index 574c113..7cc3f43 100644 --- a/backend/internal/domain/user.go +++ b/backend/internal/domain/user.go @@ -105,9 +105,11 @@ func ParseOnboardingStep(value string) (OnboardingStep, error) { } // PasswordHash is an Argon2id hash in the PHC string format. It is never the -// password itself. String and LogValue redact it. +// password itself. String and LogValue redact it. The string sits behind a +// pointer so that printing an enclosing struct shows only an address (see +// redactedValue). type PasswordHash struct { - phc string + phc *string } // NewPasswordHash validates the structure of a PHC string produced by the @@ -129,7 +131,7 @@ func NewPasswordHash(phc string) (PasswordHash, error) { if err != nil || len(digest) < minPasswordDigestBytes { return PasswordHash{}, invalidPasswordHash("digest must be unpadded base64 of at least 16 bytes") } - return PasswordHash{phc: phc}, nil + return PasswordHash{phc: newRedactedValue(phc)}, nil } func invalidPasswordHash(reason string) error { @@ -137,7 +139,7 @@ func invalidPasswordHash(reason string) error { } // PHC returns the encoded hash for storage and verification. -func (hash PasswordHash) PHC() string { return hash.phc } +func (hash PasswordHash) PHC() string { return redactedValue(hash.phc) } func (hash PasswordHash) String() string { return redactedSecret } @@ -148,8 +150,12 @@ func (hash PasswordHash) LogValue() slog.Value { return slog.StringValue(redacte // Format redacts every verb; without it %d would print the struct fields. func (hash PasswordHash) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } +// MarshalJSON redacts the hash in any JSON output, including a serialized +// User. +func (hash PasswordHash) MarshalJSON() ([]byte, error) { return redactedSecretJSON(), nil } + // IsZero reports a PasswordHash not built by NewPasswordHash. -func (hash PasswordHash) IsZero() bool { return hash.phc == "" } +func (hash PasswordHash) IsZero() bool { return hash.phc == nil } // Registration is the validated content of one registration request. type Registration struct { diff --git a/backend/internal/port/outbound/password.go b/backend/internal/port/outbound/password.go new file mode 100644 index 0000000..4848448 --- /dev/null +++ b/backend/internal/port/outbound/password.go @@ -0,0 +1,62 @@ +package outbound + +import ( + "context" + "errors" + "fmt" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrPasswordMismatch reports a password that does not match the hash. + // VerifyDummy ends with it whenever it completes the work. + ErrPasswordMismatch = errors.New("password does not match") + + // ErrPasswordHashCorrupt reports a stored hash that cannot be verified: + // it is not a well-formed Argon2id v19 PHC string, or its parameters are + // outside the bounds the hasher accepts. It wraps + // domain.ErrInvalidPasswordHash, which the repository returns when a + // stored hash fails domain.NewPasswordHash on read, so + // errors.Is(err, domain.ErrInvalidPasswordHash) matches both cases. It is + // a storage problem, not a wrong password. + ErrPasswordHashCorrupt = fmt.Errorf("password hash corrupt: %w", domain.ErrInvalidPasswordHash) +) + +// PasswordHasher derives and checks password hashes with a slow, salted KDF. +// +// Callers validate the password with domain.NewPassword or +// domain.ParseLoginPassword first, so the hasher only receives bounded +// input; a zero domain.Password returns an error wrapping +// domain.ErrInvalidPassword without hashing. Every derivation waits for its +// share of a fixed memory budget, which bounds the memory and CPU of +// concurrent hashing; a context that ends while waiting returns the context +// error and computes nothing. Errors never contain the password or the hash. +// +// Login (TASK-055) must answer invalid_credentials for an unknown email, a +// wrong password, and a stored hash that is invalid +// (domain.ErrInvalidPasswordHash, from the repository or from Verify). For +// an invalid hash it must also log an error and call VerifyDummy, because a +// corrupt hash is refused without a derivation and would otherwise answer +// faster than a real check. +type PasswordHasher interface { + // Hash returns a new hash with a fresh random salt and the current + // parameters. + Hash(ctx context.Context, password domain.Password) (domain.PasswordHash, error) + + // Verify returns nil when password matches stored. needsRehash then + // reports that stored was made with other parameters, salt length, or key + // length than the current ones, so a login can store Hash(password) in + // its place. A wrong password returns ErrPasswordMismatch and a malformed + // or out-of-bounds hash returns ErrPasswordHashCorrupt without a + // derivation; needsRehash is false with any error. + Verify(ctx context.Context, password domain.Password, stored domain.PasswordHash) (needsRehash bool, err error) + + // VerifyDummy does the same work as Verify against a hash with the current + // parameters that no password matches. It returns ErrPasswordMismatch + // after the work, the context error when the context ended before the + // derivation, or domain.ErrInvalidPassword for a zero password; it never + // returns nil. A login calls it for an unknown email so that the response + // time does not reveal whether the account exists. + VerifyDummy(ctx context.Context, password domain.Password) error +} diff --git a/backend/internal/usecase/identity/.gitkeep b/backend/internal/usecase/identity/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/backend/internal/usecase/identity/credentials.go b/backend/internal/usecase/identity/credentials.go new file mode 100644 index 0000000..c0a2680 --- /dev/null +++ b/backend/internal/usecase/identity/credentials.go @@ -0,0 +1,39 @@ +// Package identity holds the account usecases. +package identity + +import ( + "context" + "fmt" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// Credentials applies the password rules in the order that keeps hashing +// bounded: the cheap length and encoding checks first, the expensive KDF only +// for a password that passes them. +type Credentials struct { + hasher outbound.PasswordHasher +} + +func NewCredentials(hasher outbound.PasswordHasher) *Credentials { + return &Credentials{hasher: hasher} +} + +// HashNewPassword applies the registration password policy to raw and hashes +// the normalized password. A password outside the policy returns an error +// wrapping domain.ErrInvalidPassword without calling the hasher. Errors +// never contain raw. Registration (TASK-053, not implemented yet) must call +// it on every branch before it looks up the email, so that neither the +// outcome nor the time depends on whether the account exists. +func (credentials *Credentials) HashNewPassword(ctx context.Context, raw string) (domain.PasswordHash, error) { + password, err := domain.NewPassword(raw) + if err != nil { + return domain.PasswordHash{}, fmt.Errorf("Credentials.HashNewPassword - validate password: %w", err) + } + hash, err := credentials.hasher.Hash(ctx, password) + if err != nil { + return domain.PasswordHash{}, fmt.Errorf("Credentials.HashNewPassword - hash password: %w", err) + } + return hash, nil +} diff --git a/backend/internal/usecase/identity/credentials_test.go b/backend/internal/usecase/identity/credentials_test.go new file mode 100644 index 0000000..d112ae5 --- /dev/null +++ b/backend/internal/usecase/identity/credentials_test.go @@ -0,0 +1,83 @@ +package identity + +import ( + "bytes" + "context" + "errors" + "log/slog" + "strings" + "testing" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// countingHasher records calls so a test can prove that validation stops a +// password before any hashing. +type countingHasher struct { + hashCalls int + hashed domain.Password +} + +func (hasher *countingHasher) Hash(_ context.Context, password domain.Password) (domain.PasswordHash, error) { + hasher.hashCalls++ + hasher.hashed = password + return domain.NewPasswordHash("$argon2id$v=19$m=65536,t=3,p=4$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g") +} + +func (hasher *countingHasher) Verify(context.Context, domain.Password, domain.PasswordHash) (bool, error) { + return false, errors.New("countingHasher.Verify - not used") +} + +func (hasher *countingHasher) VerifyDummy(context.Context, domain.Password) error { + return errors.New("countingHasher.VerifyDummy - not used") +} + +var _ outbound.PasswordHasher = (*countingHasher)(nil) + +func TestHashNewPasswordRefusesAnOversizedPasswordBeforeHashing(t *testing.T) { + const marker = "do-not-log-this-password-" + tests := map[string]string{ + "129 code points": marker + strings.Repeat("x", 129-len(marker)), + "over the raw byte cap": marker + strings.Repeat("\U0001F600", 200), + "one megabyte": marker + strings.Repeat("y", 1<<20), + "too long after normalization": marker + strings.Repeat("fi", 60), + } + for name, raw := range tests { + hasher := &countingHasher{} + var logs bytes.Buffer + // The handling boundary logs the error as an HTTP handler would. + logger := slog.New(slog.NewJSONHandler(&logs, nil)) + + _, err := NewCredentials(hasher).HashNewPassword(context.Background(), raw) + logger.Error("registration refused", "error", err) + + if !errors.Is(err, domain.ErrInvalidPassword) { + t.Fatalf("HashNewPassword(%s) error = %v, want ErrInvalidPassword", name, err) + } + if hasher.hashCalls != 0 { + t.Fatalf("HashNewPassword(%s) called the hasher %d times, want none", name, hasher.hashCalls) + } + if strings.Contains(logs.String(), marker) || strings.Contains(err.Error(), marker) { + t.Fatalf("HashNewPassword(%s) exposed the input in the error or the log: %s", name, logs.String()) + } + } +} + +func TestHashNewPasswordRefusesAShortPasswordBeforeHashing(t *testing.T) { + hasher := &countingHasher{} + _, err := NewCredentials(hasher).HashNewPassword(context.Background(), "fourteen chars") + if !errors.Is(err, domain.ErrInvalidPassword) || hasher.hashCalls != 0 { + t.Fatalf("HashNewPassword(14 code points) = %v after %d hash calls, want ErrInvalidPassword and no call", err, hasher.hashCalls) + } +} + +func TestHashNewPasswordHashesTheNormalizedPassword(t *testing.T) { + hasher := &countingHasher{} + if _, err := NewCredentials(hasher).HashNewPassword(context.Background(), "correct horse battery"); err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + if hasher.hashCalls != 1 || hasher.hashed.Reveal() != "correct horse battery" { + t.Fatalf("hasher received %d calls, want one with the NFKC form", hasher.hashCalls) + } +} diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 89945cf..5a5857a 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -197,6 +197,12 @@ services: SMTP_USERNAME: ${SMTP_USERNAME:-} SMTP_PASSWORD: ${SMTP_PASSWORD:-} SMTP_TLS_MODE: ${SMTP_TLS_MODE:-} + # Argon2id derivations that may run at once, 64 MiB each (1 to 4). + PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-1} + # Soft Go heap limit at about 78% of the 768M container limit below; the + # rest covers goroutine stacks, runtime metadata, and non-heap memory. + # Change both together. + GOMEMLIMIT: 600MiB depends_on: postgres: condition: service_healthy diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index a3d946c..dafdbb1 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -122,7 +122,8 @@ backend/ domain/ flat package; DomainEvent, identity types usecase/health/ operational readiness usecase port/inbound/ readiness input boundary - port/outbound/ readiness, cache, object storage, transaction, outbox, identity, and mail boundaries + usecase/identity/ password validation before hashing (Credentials) + port/outbound/ readiness, cache, object storage, transaction, outbox, identity, password hashing, and mail boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -130,6 +131,7 @@ backend/ v1/ handwritten health endpoint router.go chi composition adapter/secondary/ + 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 @@ -143,11 +145,11 @@ backend/ 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`. +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`. 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, 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 `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/`. @@ -268,6 +270,19 @@ What the ports guarantee: - Unique and foreign key violations map to `ErrEmailTaken`, `ErrTokenHashConflict`, and `ErrUserNotFound` by SQLSTATE and constraint name, never by error text. - Lock order: an operation that changes both an account and its tokens locks the tokens first. A confirmation consumes the token and then verifies the account, so a re-registration or resend calls `InvalidateActive` before it updates the account or inserts a token; the opposite order can deadlock. The cleanup is the only exception: it locks the account before the tokens and sessions, which is safe because each of those locks uses SKIP LOCKED and never waits. A deadlock (SQLSTATE 40P01) or serialization failure (40001) that still happens is reported by `Transactor.WithinTransaction` and the identity repositories as `outbound.ErrTransactionConflict`; nothing was committed, and the usecase or job may retry the whole operation with backoff while staying idempotent. +### Password hashing + +Implemented (TASK-052) and tested, but not wired into bootstrap: registration (TASK-053) and login (TASK-055) will create the hasher from configuration and call it. + +- `domain.Password` holds the password normalized to Unicode NFKC. `domain.NewPassword` applies the registration policy, 15 to 128 code points after normalization; `domain.ParseLoginPassword` accepts 1 to 128. Before normalizing, both reject raw input over 512 bytes (128 code points of at most 4 UTF-8 bytes, so every value the contract schema accepts fits) and invalid UTF-8. These checks run before any hashing and fail with `domain.ErrInvalidPassword`, naming the rule but never the value. The blocklist of common or breached passwords is a separate planned check. +- The `outbound.PasswordHasher` port (`port/outbound/password.go`) has `Hash`, `Verify`, and `VerifyDummy`; the `adapter/secondary/argon2id` adapter implements it with `golang.org/x/crypto/argon2`. New hashes use Argon2id v19 with m=65536 KiB, t=3, p=4 (the second recommended option of RFC 9106, above the OWASP baseline of 19 MiB, t=2, p=1), a 16-byte salt from crypto/rand, and a 32-byte key, encoded as `$argon2id$v=19$m=65536,t=3,p=4$$` in unpadded base64, the format that `domain.NewPasswordHash` and the `users_password_hash_format` CHECK accept. One hash took about 26 to 33 ms on an Apple M5 development machine (`BenchmarkHashRecommendedParameters`, also with one CPU); this is not a production latency figure. +- Memory budget: derivations share a weighted semaphore (`golang.org/x/sync/semaphore`) of `PASSWORD_HASH_CONCURRENCY` times 64 MiB, and each holds its own memory parameter while it runs. The setting accepts 1 to 4; when unset it is the smaller of 2 and GOMAXPROCS, which Go derives from the container CPU limit. Compose passes `PASSWORD_HASH_CONCURRENCY=1` for the 1-CPU backend container, so hashes run one at a time with 64 MiB live; the maximum of 4 needs 256 MiB. Memory of a finished derivation is garbage until the next collection; `GOMEMLIMIT=600MiB` in Compose makes the collector reclaim it before the heap reaches about 78% of the 768 MiB container limit, and the rest is left for stacks and non-heap memory. Waiting calls queue in FIFO order, bounded only by their request context; request rate limiting comes with the HTTP operations. +- `Verify` parses the stored PHC string strictly and recomputes the key with the stored parameters, salt, and key length, then compares in constant time. A wrong password returns `outbound.ErrPasswordMismatch`. A malformed hash, or one outside the stored-hash bounds (memory from 8 KiB per lane to 128 MiB and within the hashing budget, 1 to 16 passes, 1 to 16 lanes, a salt of 8 to 64 bytes, a digest of 16 to 64 bytes), returns `outbound.ErrPasswordHashCorrupt` without any derivation, so a crafted row cannot demand unbounded memory or time. `ErrPasswordHashCorrupt` wraps `domain.ErrInvalidPasswordHash`, which the repository returns for a stored hash that fails `domain.NewPasswordHash`. On a match `needsRehash` reports parameters, salt, or key length that differ from the current ones, so a login can store a new hash. +- `VerifyDummy` runs `Verify` against a hash with the current parameters, a random salt, and a random digest, and returns `ErrPasswordMismatch` (or the context error). Login will call it for an unknown email, so both branches parse, wait for memory, derive, and compare alike. +- Login (TASK-055) must answer `invalid_credentials` for an unknown email, a wrong password, and an invalid stored hash (`errors.Is(err, domain.ErrInvalidPasswordHash)`, from the repository or from `Verify`); for an invalid hash it must also log an error and call `VerifyDummy`. Remaining timing differences: a corrupt hash is refused without a derivation, which `VerifyDummy` compensates, and a hash with older parameters costs what its own parameters cost until the next successful login rehashes it. +- `identity.Credentials.HashNewPassword` validates a new password and only then hashes it; registration will call it on every branch before it looks up the email. +- Errors and logs never contain the password or the hash. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken`, and `domain.EmailAddress` redact themselves in `fmt`, `slog`, and JSON output, and keep their value behind a pointer, so printing an enclosing struct, even through an unexported field, shows only an address. + ## Frontend The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index f4acea1..494c981 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -62,6 +62,8 @@ The Compose health check runs `kafka-broker-api-versions.sh` against `localhost: The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` bootstrap addresses. Compose supplies `kafka:9092`; a directly launched Go process defaults to `localhost:9092`. An explicitly empty value, an empty list entry, a missing or zero port, or a URL scheme fails configuration. The backend has no Kafka client yet: it does not wait for Kafka at startup, and `/readyz` does not check Kafka. The advertised address `kafka:9092` resolves only inside the Compose network, so direct execution needs a separately reachable broker. Redis stays a cache and is not used as a queue. +`PASSWORD_HASH_CONCURRENCY` sets the Argon2id memory budget in derivations of 64 MiB and four lanes each (from 1 to 4). Compose passes the value from `.env`, default 1, because the backend container has 1 CPU and 768 MB: a second derivation would only add 64 MiB while sharing the CPU. A directly launched backend without the variable uses the smaller of 2 and GOMAXPROCS. Further registrations and logins wait for memory until their request context ends. Compose also sets `GOMEMLIMIT=600MiB`, about 78% of the container limit, so the Go collector reclaims finished derivations before the container runs out of memory; change it together with the memory limit. The value is read and validated at startup; registration and login will use it once they are implemented. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing). + down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop. ## Mail diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index ff97aa8..6d1bed2 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. 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, 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. - 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 a home page, 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 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 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). ## Install and work loop @@ -166,6 +166,8 @@ Migration `00002_create_identity_tables.sql` creates `users`, `email_tokens`, an The database never receives a password, a raw email token, or a raw session token. Repositories take a `domain.PasswordHash` (an Argon2id v19 PHC string) and a `domain.SecretTokenHash` (the SHA-256 of a `domain.SecretToken`). Email addresses are ASCII only for now; IDN and SMTPUTF8 support is future work that needs IDNA ToASCII for the domain. `SecretToken`, `PasswordHash`, and `EmailAddress` redact themselves in `fmt` and `slog` output; `SecretToken.Reveal` and `EmailAddress.Address` return the real values where they are needed. Every stored time comes from the application clock that the caller passes, and PostgreSQL keeps microseconds. A deadlock or serialization failure is reported as `outbound.ErrTransactionConflict`, and the caller may retry the whole operation. The schema and its decisions are described in [ARCHITECTURE.md](ARCHITECTURE.md#identity-storage). +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). + ## 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 bdc3ba8..706144c 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -122,7 +122,8 @@ backend/ domain/ плоский пакет; DomainEvent, типы identity usecase/health/ operational readiness usecase port/inbound/ inbound граница readiness - port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity и почты + usecase/identity/ проверка пароля до хеширования (Credentials) + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity, хеширования паролей и почты adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -130,6 +131,7 @@ backend/ v1/ написанный вручную health endpoint router.go сборка chi router adapter/secondary/ + argon2id/ hasher паролей Argon2id с бюджетом памяти mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала ml/api/ generated client из backend/codegen/ogen-ml.yml postgres/ pool, migrator, transactor, запись outbox, репозитории identity, health check @@ -143,11 +145,11 @@ backend/ 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`. +Доменные типы лежат непосредственно в `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`. `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, 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/`. @@ -268,6 +270,19 @@ contact_grant относится к паре кандидат-компания - Нарушения уникальности и внешних ключей переводятся в `ErrEmailTaken`, `ErrTokenHashConflict` и `ErrUserNotFound` по SQLSTATE и имени ограничения, а не по тексту ошибки. - Порядок блокировок: операция, которая меняет и аккаунт, и его токены, сначала блокирует токены. Подтверждение гасит токен, а затем подтверждает аккаунт, поэтому повторная регистрация или повторная отправка вызывает `InvalidateActive` до обновления аккаунта или вставки токена; обратный порядок может привести к взаимной блокировке. Единственное исключение - очистка: она блокирует аккаунт раньше токенов и сессий, и это безопасно, потому что каждая из этих блокировок берется с SKIP LOCKED и никогда не ждет. Если взаимная блокировка (SQLSTATE 40P01) или ошибка сериализации (40001) все же случится, `Transactor.WithinTransaction` и репозитории identity сообщают ее как `outbound.ErrTransactionConflict`; ничего не зафиксировано, и usecase или job может повторить всю операцию с паузой, оставаясь идемпотентным. +### Хеширование паролей + +Реализовано (TASK-052) и покрыто тестами, но в bootstrap не подключено: регистрация (TASK-053) и вход (TASK-055) будут создавать hasher из конфигурации и вызывать его. + +- `domain.Password` хранит пароль, нормализованный в Unicode NFKC. `domain.NewPassword` применяет политику регистрации: от 15 до 128 кодовых точек после нормализации; `domain.ParseLoginPassword` принимает от 1 до 128. До нормализации оба отклоняют исходный ввод длиннее 512 байт (128 кодовых точек по 4 байта UTF-8 максимум, поэтому любое значение, принятое схемой контракта, помещается) и некорректный UTF-8. Эти проверки выполняются до любого хеширования и завершаются `domain.ErrInvalidPassword` с названием правила, но без значения. Blocklist распространенных и утекших паролей - отдельная запланированная проверка. +- Порт `outbound.PasswordHasher` (`port/outbound/password.go`) содержит `Hash`, `Verify` и `VerifyDummy`; адаптер `adapter/secondary/argon2id` реализует его через `golang.org/x/crypto/argon2`. Новые хеши используют Argon2id v19 с m=65536 KiB, t=3, p=4 (второй рекомендованный вариант RFC 9106, выше базового уровня OWASP 19 MiB, t=2, p=1), соль 16 байт из crypto/rand и ключ 32 байта в формате `$argon2id$v=19$m=65536,t=3,p=4$$` в base64 без дополнения - этот формат принимают `domain.NewPasswordHash` и CHECK `users_password_hash_format`. Один хеш занял примерно 26-33 ms на машине разработчика Apple M5 (`BenchmarkHashRecommendedParameters`, в том числе на одном CPU); это не измерение задержки в production. +- Бюджет памяти: вычисления делят взвешенный семафор (`golang.org/x/sync/semaphore`) размером `PASSWORD_HASH_CONCURRENCY`, умноженное на 64 MiB, и каждое держит свой параметр памяти, пока выполняется. Настройка принимает от 1 до 4; если она не задана, берется меньшее из 2 и GOMAXPROCS, который Go выводит из лимита CPU контейнера. Compose передает `PASSWORD_HASH_CONCURRENCY=1` для backend-контейнера с 1 CPU, поэтому хеши вычисляются по одному и занимают 64 MiB живой памяти; максимум 4 требует 256 MiB. Память завершенного вычисления остается мусором до следующей сборки; `GOMEMLIMIT=600MiB` в Compose заставляет сборщик освободить ее раньше, чем куча дойдет примерно до 78% лимита контейнера 768 MiB, а остаток приходится на стеки и память вне кучи. Ожидающие вызовы стоят в очереди FIFO, ограниченной только контекстом запроса; ограничение частоты запросов появится вместе с HTTP-операциями. +- `Verify` строго разбирает сохраненную строку PHC, заново вычисляет ключ с сохраненными параметрами, солью и длиной ключа и сравнивает за постоянное время. Неверный пароль возвращает `outbound.ErrPasswordMismatch`. Некорректный хеш или хеш вне границ для сохраненных значений (память от 8 KiB на lane до 128 MiB и в пределах бюджета хеширования, от 1 до 16 проходов, от 1 до 16 lanes, соль 8-64 байта, digest 16-64 байта) возвращает `outbound.ErrPasswordHashCorrupt` без вычисления, поэтому подделанная строка не может потребовать неограниченную память или время. `ErrPasswordHashCorrupt` оборачивает `domain.ErrInvalidPasswordHash`, который репозиторий возвращает для сохраненного хеша, не прошедшего `domain.NewPasswordHash`. При совпадении `needsRehash` сообщает, что параметры, соль или длина ключа отличаются от текущих, и вход может сохранить новый хеш. +- `VerifyDummy` выполняет `Verify` для хеша с текущими параметрами, случайной солью и случайным digest и возвращает `ErrPasswordMismatch` (или ошибку контекста). Вход будет вызывать его для неизвестного email, поэтому обе ветки одинаково разбирают хеш, ждут память, вычисляют и сравнивают. +- Вход (TASK-055) должен отвечать `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша (`errors.Is(err, domain.ErrInvalidPasswordHash)`, из репозитория или из `Verify`); для некорректного хеша он также должен записать ошибку в лог и вызвать `VerifyDummy`. Оставшиеся различия во времени: поврежденный хеш отклоняется без вычисления, что компенсирует `VerifyDummy`, а хеш со старыми параметрами стоит столько, сколько стоят его параметры, пока следующий успешный вход его не перехеширует. +- `identity.Credentials.HashNewPassword` проверяет новый пароль и только потом хеширует его; регистрация будет вызывать его в каждой ветке до поиска email. +- Ошибки и логи никогда не содержат пароль или хеш. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken` и `domain.EmailAddress` скрывают значение в выводе `fmt`, `slog` и JSON и хранят его за указателем, поэтому при печати внешней структуры, даже через неэкспортируемое поле, виден только адрес. + ## Frontend Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index f810b1f..561a701 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -64,6 +64,8 @@ Compose healthcheck запускает `kafka-broker-api-versions.sh` проти Backend получает `KAFKA_BROKERS` - список адресов bootstrap в формате `host:port` через запятую. Compose задает `kafka:9092`; прямой запуск Go по умолчанию использует `localhost:9092`. Явно пустое значение, пустой элемент списка, отсутствующий или нулевой порт либо схема URL приводят к ошибке конфигурации. Kafka клиента в backend пока нет: backend не ждет Kafka при старте, а `/readyz` ее не проверяет. Объявленный адрес `kafka:9092` разрешается только внутри Compose сети, поэтому для прямого запуска нужен отдельно доступный брокер. Redis остается кешем и не используется как очередь. +`PASSWORD_HASH_CONCURRENCY` задает бюджет памяти Argon2id в вычислениях по 64 MiB и четыре lanes каждое (от 1 до 4). Compose передает значение из `.env`, по умолчанию 1, потому что у backend-контейнера 1 CPU и 768 MB: второе вычисление только добавило бы 64 MiB, деля тот же CPU. Backend, запущенный напрямую без переменной, берет меньшее из 2 и GOMAXPROCS. Следующие регистрации и входы ждут память, пока не завершится контекст запроса. Compose также задает `GOMEMLIMIT=600MiB`, примерно 78% лимита контейнера, чтобы сборщик Go освобождал память завершенных вычислений раньше, чем контейнеру ее не хватит; меняйте его вместе с лимитом памяти. Значение читается и проверяется при старте; регистрация и вход начнут его использовать, когда будут реализованы. См. [ARCHITECTURE.md](ARCHITECTURE.md#хеширование-паролей). + down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова. ## Почта diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index f1ff49e..26859c0 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. 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`), другой бизнес-схемы нет; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей, содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы @@ -166,6 +166,8 @@ goose выполняет каждую миграцию в отдельной т База данных никогда не получает пароль, исходный email-токен или исходный токен сессии. Репозитории принимают `domain.PasswordHash` (строку PHC Argon2id v19) и `domain.SecretTokenHash` (SHA-256 от `domain.SecretToken`). Email-адреса пока принимаются только в ASCII; поддержка IDN и SMTPUTF8 - будущая работа, для которой нужен IDNA ToASCII для домена. `SecretToken`, `PasswordHash` и `EmailAddress` скрывают значение в выводе `fmt` и `slog`; `SecretToken.Reveal` и `EmailAddress.Address` возвращают настоящие значения там, где они нужны. Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, а PostgreSQL хранит микросекунды. Взаимная блокировка или ошибка сериализации сообщается как `outbound.ErrTransactionConflict`, и вызывающий код может повторить всю операцию. Схема и принятые решения описаны в [ARCHITECTURE.md](ARCHITECTURE.md#хранение-identity). +Пароль попадает в 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#хеширование-паролей). + ## Читаемость Go-кода - Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна. From 0e2a3b02abaca608c104340ebd8ae2ae01e4fd60 Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 01:09:08 +0300 Subject: [PATCH 010/143] feat(frontend): add cabinet shells, brand tokens, and state primitives --- .agents/standards/frontend.md | 4 +- docs/en/ARCHITECTURE.md | 2 +- docs/en/DEVELOPMENT.md | 6 +- docs/ru/ARCHITECTURE.md | 2 +- docs/ru/DEVELOPMENT.md | 6 +- frontend/README.en.md | 74 ++++++- frontend/README.md | 74 ++++++- frontend/index.html | 2 +- frontend/src/app/main.tsx | 2 + .../src/app/providers/query-client.test.tsx | 108 ++++++++++ frontend/src/app/providers/query-client.ts | 45 ++++ frontend/src/app/router/routes.test.tsx | 134 ++++++++++++ frontend/src/app/router/routes.tsx | 89 ++++++++ frontend/src/app/ui/app.tsx | 23 +-- frontend/src/app/ui/root-layout.tsx | 11 + frontend/src/app/ui/route-error-page.tsx | 24 +++ frontend/src/app/ui/styles.css | 79 +++++-- frontend/src/pages/home/index.ts | 1 - .../src/pages/home/ui/home-page.module.css | 54 ----- frontend/src/pages/home/ui/home-page.tsx | 16 -- frontend/src/pages/not-found/index.ts | 1 + .../src/pages/not-found/ui/not-found-page.tsx | 29 +++ frontend/src/pages/placeholder/index.ts | 2 + .../src/pages/placeholder/model/screens.ts | 142 +++++++++++++ .../ui/placeholder-page.module.css | 43 ++++ .../pages/placeholder/ui/placeholder-page.tsx | 38 ++++ frontend/src/pages/status/index.ts | 1 + .../pages/status/ui/state-fixtures.module.css | 11 + .../src/pages/status/ui/state-fixtures.tsx | 131 ++++++++++++ frontend/src/pages/status/ui/status-page.tsx | 20 ++ frontend/src/pages/welcome/index.ts | 1 + .../pages/welcome/ui/welcome-page.module.css | 79 +++++++ .../src/pages/welcome/ui/welcome-page.tsx | 56 +++++ frontend/src/shared/config/index.ts | 1 + frontend/src/shared/config/paths.ts | 28 +++ frontend/src/shared/ui/.gitkeep | 0 .../src/shared/ui/brand/brand-logo.module.css | 45 ++++ frontend/src/shared/ui/brand/brand-logo.tsx | 36 ++++ .../src/shared/ui/brand/fsp-logo-on-dark.svg | 12 ++ .../src/shared/ui/brand/fsp-logo-on-light.svg | 12 ++ .../src/shared/ui/button/button.module.css | 63 ++++++ frontend/src/shared/ui/button/button.tsx | 61 ++++++ frontend/src/shared/ui/index.ts | 24 +++ .../src/shared/ui/layout/layout.module.css | 117 +++++++++++ frontend/src/shared/ui/layout/page.tsx | 32 +++ frontend/src/shared/ui/layout/section.tsx | 29 +++ frontend/src/shared/ui/layout/stack.tsx | 35 ++++ .../src/shared/ui/link/text-link.module.css | 67 ++++++ frontend/src/shared/ui/link/text-link.tsx | 31 +++ .../ui/main-region/main-region.module.css | 9 + .../src/shared/ui/main-region/main-region.tsx | 41 ++++ frontend/src/shared/ui/mono/mono.module.css | 12 ++ frontend/src/shared/ui/mono/mono.tsx | 18 ++ .../shared/ui/skip-link/skip-link.module.css | 22 ++ .../src/shared/ui/skip-link/skip-link.tsx | 26 +++ .../shared/ui/status-view/describe-error.ts | 130 ++++++++++++ .../src/shared/ui/status-view/query-view.tsx | 55 +++++ .../ui/status-view/status-view.module.css | 146 +++++++++++++ .../ui/status-view/status-view.test.tsx | 126 +++++++++++ .../src/shared/ui/status-view/status-view.tsx | 195 ++++++++++++++++++ frontend/src/shared/ui/theme/fonts.css | 20 ++ .../ui/theme/fonts/JetBrainsMono-AUTHORS.txt | 10 + .../ui/theme/fonts/JetBrainsMono-Bold.woff2 | Bin 0 -> 94588 bytes .../ui/theme/fonts/JetBrainsMono-OFL.txt | 93 +++++++++ .../theme/fonts/JetBrainsMono-Regular.woff2 | Bin 0 -> 92164 bytes frontend/src/shared/ui/theme/tokens.css | 114 ++++++++++ .../ui/trust-level/trust-level-labels.ts | 13 ++ .../ui/trust-level/trust-level.module.css | 34 +++ .../ui/trust-level/trust-level.test.tsx | 31 +++ .../src/shared/ui/trust-level/trust-level.tsx | 41 ++++ .../visually-hidden.module.css | 12 ++ .../ui/visually-hidden/visually-hidden.tsx | 11 + frontend/src/widgets/.gitkeep | 0 frontend/src/widgets/candidate-shell/index.ts | 1 + .../ui/candidate-shell.module.css | 52 +++++ .../candidate-shell/ui/candidate-shell.tsx | 42 ++++ frontend/src/widgets/employer-shell/index.ts | 1 + .../ui/employer-shell.module.css | 76 +++++++ .../employer-shell/ui/employer-shell.tsx | 41 ++++ frontend/src/widgets/public-shell/index.ts | 1 + .../public-shell/ui/public-shell.module.css | 42 ++++ .../widgets/public-shell/ui/public-shell.tsx | 36 ++++ frontend/src/widgets/system-status/index.ts | 1 + .../system-status/ui/system-status.module.css | 21 ++ .../system-status/ui/system-status.tsx | 50 +++++ 85 files changed, 3313 insertions(+), 113 deletions(-) create mode 100644 frontend/src/app/providers/query-client.test.tsx create mode 100644 frontend/src/app/providers/query-client.ts create mode 100644 frontend/src/app/router/routes.test.tsx create mode 100644 frontend/src/app/router/routes.tsx create mode 100644 frontend/src/app/ui/root-layout.tsx create mode 100644 frontend/src/app/ui/route-error-page.tsx delete mode 100644 frontend/src/pages/home/index.ts delete mode 100644 frontend/src/pages/home/ui/home-page.module.css delete mode 100644 frontend/src/pages/home/ui/home-page.tsx create mode 100644 frontend/src/pages/not-found/index.ts create mode 100644 frontend/src/pages/not-found/ui/not-found-page.tsx create mode 100644 frontend/src/pages/placeholder/index.ts create mode 100644 frontend/src/pages/placeholder/model/screens.ts create mode 100644 frontend/src/pages/placeholder/ui/placeholder-page.module.css create mode 100644 frontend/src/pages/placeholder/ui/placeholder-page.tsx create mode 100644 frontend/src/pages/status/index.ts create mode 100644 frontend/src/pages/status/ui/state-fixtures.module.css create mode 100644 frontend/src/pages/status/ui/state-fixtures.tsx create mode 100644 frontend/src/pages/status/ui/status-page.tsx create mode 100644 frontend/src/pages/welcome/index.ts create mode 100644 frontend/src/pages/welcome/ui/welcome-page.module.css create mode 100644 frontend/src/pages/welcome/ui/welcome-page.tsx create mode 100644 frontend/src/shared/config/index.ts create mode 100644 frontend/src/shared/config/paths.ts delete mode 100644 frontend/src/shared/ui/.gitkeep create mode 100644 frontend/src/shared/ui/brand/brand-logo.module.css create mode 100644 frontend/src/shared/ui/brand/brand-logo.tsx create mode 100644 frontend/src/shared/ui/brand/fsp-logo-on-dark.svg create mode 100644 frontend/src/shared/ui/brand/fsp-logo-on-light.svg create mode 100644 frontend/src/shared/ui/button/button.module.css create mode 100644 frontend/src/shared/ui/button/button.tsx create mode 100644 frontend/src/shared/ui/index.ts create mode 100644 frontend/src/shared/ui/layout/layout.module.css create mode 100644 frontend/src/shared/ui/layout/page.tsx create mode 100644 frontend/src/shared/ui/layout/section.tsx create mode 100644 frontend/src/shared/ui/layout/stack.tsx create mode 100644 frontend/src/shared/ui/link/text-link.module.css create mode 100644 frontend/src/shared/ui/link/text-link.tsx create mode 100644 frontend/src/shared/ui/main-region/main-region.module.css create mode 100644 frontend/src/shared/ui/main-region/main-region.tsx create mode 100644 frontend/src/shared/ui/mono/mono.module.css create mode 100644 frontend/src/shared/ui/mono/mono.tsx create mode 100644 frontend/src/shared/ui/skip-link/skip-link.module.css create mode 100644 frontend/src/shared/ui/skip-link/skip-link.tsx create mode 100644 frontend/src/shared/ui/status-view/describe-error.ts create mode 100644 frontend/src/shared/ui/status-view/query-view.tsx create mode 100644 frontend/src/shared/ui/status-view/status-view.module.css create mode 100644 frontend/src/shared/ui/status-view/status-view.test.tsx create mode 100644 frontend/src/shared/ui/status-view/status-view.tsx create mode 100644 frontend/src/shared/ui/theme/fonts.css create mode 100644 frontend/src/shared/ui/theme/fonts/JetBrainsMono-AUTHORS.txt create mode 100644 frontend/src/shared/ui/theme/fonts/JetBrainsMono-Bold.woff2 create mode 100644 frontend/src/shared/ui/theme/fonts/JetBrainsMono-OFL.txt create mode 100644 frontend/src/shared/ui/theme/fonts/JetBrainsMono-Regular.woff2 create mode 100644 frontend/src/shared/ui/theme/tokens.css create mode 100644 frontend/src/shared/ui/trust-level/trust-level-labels.ts create mode 100644 frontend/src/shared/ui/trust-level/trust-level.module.css create mode 100644 frontend/src/shared/ui/trust-level/trust-level.test.tsx create mode 100644 frontend/src/shared/ui/trust-level/trust-level.tsx create mode 100644 frontend/src/shared/ui/visually-hidden/visually-hidden.module.css create mode 100644 frontend/src/shared/ui/visually-hidden/visually-hidden.tsx delete mode 100644 frontend/src/widgets/.gitkeep create mode 100644 frontend/src/widgets/candidate-shell/index.ts create mode 100644 frontend/src/widgets/candidate-shell/ui/candidate-shell.module.css create mode 100644 frontend/src/widgets/candidate-shell/ui/candidate-shell.tsx create mode 100644 frontend/src/widgets/employer-shell/index.ts create mode 100644 frontend/src/widgets/employer-shell/ui/employer-shell.module.css create mode 100644 frontend/src/widgets/employer-shell/ui/employer-shell.tsx create mode 100644 frontend/src/widgets/public-shell/index.ts create mode 100644 frontend/src/widgets/public-shell/ui/public-shell.module.css create mode 100644 frontend/src/widgets/public-shell/ui/public-shell.tsx create mode 100644 frontend/src/widgets/system-status/index.ts create mode 100644 frontend/src/widgets/system-status/ui/system-status.module.css create mode 100644 frontend/src/widgets/system-status/ui/system-status.tsx diff --git a/.agents/standards/frontend.md b/.agents/standards/frontend.md index 2494630..7988bdc 100644 --- a/.agents/standards/frontend.md +++ b/.agents/standards/frontend.md @@ -10,6 +10,8 @@ Use the generated Orval client as the contract-derived transport surface. Put sh Model server data in the selected query library and form drafts in form state. Avoid adding a second store for data already owned by the server cache. Show loading, empty, error, retry, and forbidden states as product flows are implemented. -MSW fixtures are test inputs. They do not prove that a backend workflow exists. The current page is a minimal status view; do not document full candidate or employer interfaces as implemented. +MSW fixtures are test inputs. They do not prove that a backend workflow exists. The current interface is a scaffold: a React Router data router with public routes and separate candidate and employer cabinet shells, shared UI tokens, and primitives for loading, empty, error, forbidden, and saving states. The sign-in, registration, email confirmation, support, and all cabinet screens are placeholders; business screens are later tasks, so do not document candidate or employer workflows as implemented. /status is a technical API liveness page, not a product readiness indicator. + +Vitest runs in the Node environment without a DOM. Component and route tests check rendered markup and query behavior; clicks, keyboard focus, and layout are verified manually in a browser until the planned Playwright suite exists. All source comments are in English. User-facing interface copy can be localized. diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index dafdbb1..4a6916e 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -4,7 +4,7 @@ This document separates the target product architecture from the technical scaff ## Current scaffold -The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a minimal React status page, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port. +The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port. This is an operational scaffold. It has no registration, roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, or FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index 6d1bed2..efe9ff0 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -50,7 +50,7 @@ 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. - 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 a home page, a generated API client, and MSW handlers. +- 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`). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the backend has no Go Kafka client, topics, or readiness check for Kafka. - 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. @@ -136,7 +136,9 @@ Redis connects through the outbound cache port and `backend/internal/adapter/sec S3 storage connects through the outbound `ObjectStorage` port and `backend/internal/adapter/secondary/seaweedfs/`. SeaweedFS is a separate server; AWS SDK for Go v2 is the Go client inside the adapter. Put/Get stream content; Put requires a known byte length, and callers must close the body returned by Get. The Get timeout covers reading the response body. The adapter bounds operation time and distinguishes a missing object from a service error. The container initializes its bucket; Go checks it with HeadBucket instead of creating infrastructure while handling requests. Do not add direct Nginx delivery of private files or product upload/download endpoints without access rules. -The frontend is a React/Vite SPA. Keep FSD boundaries as product screens are added. Generated transport types are not automatically entity models. MSW supports UI development; its fixtures do not prove that the API is implemented. +The frontend is a React/Vite SPA. Keep FSD boundaries as product screens are added. + +Implemented frontend scaffold: a React Router data router with public routes and separate candidate and employer cabinet shells, a TanStack Query client over the shared same-origin `apiRequest`, brand tokens in CSS variables, and shared primitives for loading, empty, error, forbidden, and saving states. JetBrains Mono 2.304 is self-hosted from the brandbook with its OFL license. Sign-in, registration, email confirmation, support, and cabinet screens are placeholders; business screens are later tasks. /status is a technical API liveness page, not product readiness. Vitest runs in the Node environment without a DOM, so clicks and keyboard focus are verified manually in a browser until the Playwright suite exists. See [frontend/README.en.md](../../frontend/README.en.md). Generated transport types are not automatically entity models. MSW supports UI development; its fixtures do not prove that the API is implemented. ML runs as a separate FastAPI process. It currently provides operational health/readiness only. Readiness stays at 503 without a model. Do not add placeholder inference that looks like a real result. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 706144c..72fa4fd 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -4,7 +4,7 @@ ## Что работает сейчас -Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, минимальную React-страницу состояния, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту. +Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-каркас интерфейса с публичными страницами и двумя оболочками кабинетов с экранами-заготовками, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту. Это технический каркас. В нем нет регистрации, ролей, профилей, тестов, грейдов, поиска, приглашений, загрузки/анализа резюме, PDF или интеграции с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 26859c0..9e1d8cd 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -50,7 +50,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 не подключен. - Почта: 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. +- 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`). - Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в backend нет Go клиента Kafka, топиков и проверки Kafka в readiness. - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md). @@ -136,7 +136,9 @@ Redis подключен через outbound-порт кеша и `backend/inter S3-хранилище подключено через outbound-порт `ObjectStorage` и `backend/internal/adapter/secondary/seaweedfs/`. SeaweedFS - отдельный сервер, а AWS SDK for Go v2 - клиент Go внутри адаптера. Put/Get передают содержимое потоком; Put требует известный размер в байтах, а вызывающий код обязан закрыть тело, возвращенное Get. Таймаут Get действует до завершения чтения тела. Адаптер ограничивает время операций и отличает отсутствие объекта от ошибки сервиса. Bucket создается при запуске контейнера; Go проверяет его через HeadBucket, не создавая инфраструктуру при обработке запросов. Не добавляйте прямую выдачу приватных файлов Nginx или продуктовые upload/download endpoints без правил доступа. -Frontend строится как React/Vite SPA. При разработке продуктовых экранов соблюдайте FSD границы. Generated API transport не превращается в entity model сам по себе. MSW полезен для интерфейсной разработки, но его fixture не подтверждает API реализации. +Frontend строится как React/Vite SPA. При разработке продуктовых экранов соблюдайте FSD границы. + +Реализованный каркас frontend: data router React Router с публичными маршрутами и отдельными оболочками кабинетов кандидата и работодателя, клиент TanStack Query поверх общего `apiRequest` того же origin, токены бренда в CSS variables и общие примитивы состояний загрузки, пустого результата, ошибки, запрета доступа и сохранения. JetBrains Mono 2.304 раздается с нашего сервера из брендбука вместе с лицензией OFL. Вход, регистрация, подтверждение почты, поддержка и экраны кабинетов - заготовки; бизнес-экраны делаются отдельными задачами. /status - техническая страница доступности API, а не показатель готовности продукта. Vitest работает в окружении Node без DOM, поэтому нажатия и фокус клавиатуры проверяются вручную в браузере, пока нет набора Playwright. Подробнее: [frontend/README.md](../../frontend/README.md). Generated API transport не превращается в entity model сам по себе. MSW полезен для интерфейсной разработки, но его fixture не подтверждает API реализации. ML - отдельный FastAPI процесс. Сейчас он предоставляет только operational health/readiness. Readiness остается 503 без модели. Не добавляйте placeholder inference, который выглядит как рабочий результат. diff --git a/frontend/README.en.md b/frontend/README.en.md index 5f167d9..79bf206 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -2,13 +2,81 @@ [Русский](README.md) | English -A React and TypeScript SPA built with Vite and organized using FSD. The current page shows backend status; candidate and employer dashboards are not implemented yet. +A React and TypeScript SPA built with Vite and organized using FSD. The interface scaffold exists: public pages and the candidate and employer cabinet shells with navigation, shared screen states, and brand tokens. Every screen is a placeholder; business screens are separate tasks. -- `src/app/` starts the application; `pages/`, `widgets/`, `features/`, and `entities/` are the interface layers. -- `src/shared/` contains shared components and the API client, including generated endpoints, Zod schemas, and MSW mocks. +- `src/app/` starts the application: the route tree (`router/`), the query client (`providers/`), global styles, and the route error page. +- `src/pages/` holds pages: `welcome` (start page), `placeholder` (screen placeholders and the screen map), `status` (technical status), `not-found`. +- `src/widgets/` holds shells: `public-shell`, `candidate-shell`, `employer-shell`, plus the technical `system-status` widget. +- `src/features/` and `src/entities/` are still empty. +- `src/shared/ui/` holds design tokens, fonts, logos, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks. - `codegen/orval.config.ts` configures generation from the shared OpenAPI contract. - `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture. From the repository root, `make -C frontend dev` starts development and `make -C frontend check` runs checks and builds the app. In Docker, Nginx serves the built files using configuration from `deploy/nginx/`. +## Routes + +| Group | Paths | Shell | +| --------- | -------------------------------------------------------------------------------------------------------------- | ---------------- | +| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | +| Candidate | `/candidate` and `/candidate/` + `onboarding`, `profile`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` | +| Employer | `/employer` (redirects to `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` | + +Each group has its own not-found page. Paths are defined once in `shared/config/paths.ts`. The router uses React Router data APIs (`createBrowserRouter`): a route-level error boundary, loader redirects, and later `lazy` code splitting for cabinets. Loaders do not fetch data; server data belongs to TanStack Query. Access control is not implemented in the interface; the server enforces it. + +`/status` is a service page: it checks `/api/v1/healthz` and is linked from the public footer only. It is not a product readiness indicator. In development mode the same page shows a gallery of states built from local fixtures (an error with retry, loading, empty, forbidden, saving, trust levels); production builds do not include it. + +## Server data + +Generated Orval hooks call the shared same-origin `apiRequest` client, so the `QueryClient` has no default query function. Defaults in `app/providers/query-client.ts`: + +- retries: up to two, only for no response (status 0) and 5xx except 501; 4xx and `invalid_response` fail at once; +- `staleTime` of 30 s; window focus does not refetch, and screens that need fresh data opt in per query; +- mutations do not retry until the API supports `Idempotency-Key`. + +## Tokens and theme + +Tokens live in `shared/ui/theme/tokens.css`: palette, semantic colors, type scale, spacing in 4px steps, radii, lines, focus ring, content widths, and motion. Breakpoints are fixed in media queries: 360px minimum, 768px tablet (`48rem`), 1024px desktop navigation (`64rem`), and 1280px verified wide layout. + +Only the light theme ships. The graphite employer sidebar is a local dark region with its own checked text, link, and focus colors. A dark theme must define and check its own pairs instead of inheriting the light accents. + +WCAG 2.2 contrast of the pairs in use: + +| Foreground | Background | Ratio | Use | +| ---------- | ---------- | ----- | ----------------------------------------- | +| #1B1C21 | #FFFFFF | 17.01 | Text on surfaces | +| #1B1C21 | #EDEDED | 14.53 | Text on the canvas | +| #2D2E37 | #FFFFFF | 13.48 | Secondary text | +| #2D2E37 | #EDEDED | 11.52 | Secondary text on the canvas | +| #402FFF | #FFFFFF | 6.84 | Links, active navigation, focus ring | +| #402FFF | #EDEDED | 5.85 | Labels and links on the canvas | +| #FFFFFF | #402FFF | 6.84 | Primary button, skip link | +| #EDEDED | #1B1C21 | 14.53 | Employer sidebar text | +| #FFFFFF | #1B1C21 | 17.01 | Active item and focus ring in the sidebar | +| #EC1D35 | #FFFFFF | 4.38 | Error graphics only (needs 3:1) | +| #FFFFFF | #EC1D35 | 4.38 | Glyph inside the error mark (graphic) | + +Excluded pairs: red is not used for body text (4.38 is below 4.5); #402FFF on #1B1C21 (2.49) and on #2D2E37 (1.97) is not used; grey #C8C9CA (1.66 on white) is only for decorative dividers. + +## Fonts and logos + +JetBrains Mono 2.304 (SIL OFL 1.1) is self-hosted from `requirements/brandbook/`: regular and bold woff2 files plus the license and authors list live in `shared/ui/theme/fonts/`. The font is used through `Mono` for numbers, scores, codes, and pseudonyms. Text uses the system font stack: Unbounded and Golos Text are not added, because their files and licenses are not in the repository. + +The header uses the FSP brandbook logo: `logo_02w.svg` on light backgrounds and `logo_01.svg` on the graphite sidebar, unchanged, with the product name beside it. + +## Shared components + +- `Page`, `Section`, `Stack`: page layout; `Page` owns the only `h1` and the document title. +- `Button`, `ButtonLink`, `TextLink`, `NavItem`: controls with text labels; `NavItem` marks the active section with `aria-current`, a bar, and weight. +- `StatusView`, `LoadingState`, `EmptyState`, `ErrorState`, `ForbiddenState`, `SavingStatus`: screen states. Each state has its own shape and text. `ErrorState` shows the code, status, server text, and request ID as plain text and offers a retry. +- `QueryView`: maps a query result to loading, error, forbidden (401 and 403 without retry), empty, or data. +- `TrustLevel`: an empty mark, ring, partial fill, or full mark with a visible label. +- `Mono`, `VisuallyHidden`, `SkipLink`, `MainRegion`, `BrandLogo`. + +Accessibility: every shell starts with a skip link to `main`, has landmarks and a visible focus ring, and moves focus to `main` after navigation. Animations respect `prefers-reduced-motion`. + +## Tests + +Vitest runs in the Node environment with no DOM library. Routes are rendered through React Router's static handler and checked as HTML: shells, landmarks, the skip link, the active item, redirects, and not-found pages. State tests render components to markup; the query-error test runs the real `QueryClient` with the generated health operation and a stubbed `fetch`. Clicks and focus movement are checked manually in a browser; automated interaction tests need a DOM environment, which is a separate dependency decision. + See the [development guide](../docs/en/DEVELOPMENT.md). diff --git a/frontend/README.md b/frontend/README.md index d64e227..e642849 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -2,13 +2,81 @@ Русский | [English](README.en.md) -SPA на React и TypeScript со сборкой Vite и структурой FSD. Сейчас интерфейс показывает состояние backend; кабинеты кандидата и работодателя пока не реализованы. +SPA на React и TypeScript со сборкой Vite и структурой FSD. Готов каркас интерфейса: публичные страницы и оболочки кабинетов кандидата и работодателя с навигацией, общими состояниями экранов и токенами бренда. Все экраны - заготовки; бизнес-экраны делаются отдельными задачами. -- `src/app/` - запуск приложения; `pages/`, `widgets/`, `features/`, `entities/` - слои интерфейса. -- `src/shared/` - общие компоненты и API-клиент, включая сгенерированные endpoints, схемы Zod и MSW-моки. +- `src/app/` - запуск приложения: дерево маршрутов (`router/`), клиент запросов (`providers/`), глобальные стили и страница ошибки маршрута. +- `src/pages/` - страницы: `welcome` (стартовая), `placeholder` (заготовки экранов и карта экранов), `status` (технический статус), `not-found`. +- `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, а также технический виджет `system-status`. +- `src/features/` и `src/entities/` пока пусты. +- `src/shared/ui/` - токены дизайна, шрифты, логотипы и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками. - `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта. - `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2. Из корня: `make -C frontend dev` запускает разработку, `make -C frontend check` - проверки и сборку. В Docker собранные файлы раздает Nginx с конфигурацией из `deploy/nginx/`. +## Маршруты + +| Группа | Пути | Оболочка | +| ------------ | ------------------------------------------------------------------------------------------------------------------- | ---------------- | +| Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | +| Кандидат | `/candidate` и `/candidate/` + `onboarding`, `profile`, `assessment`, `results`, `invitations`, `privacy` | `CandidateShell` | +| Работодатель | `/employer` (перенаправляет на `/employer/company`), `/employer/` + `company`, `needs`, `candidates`, `invitations` | `EmployerShell` | + +У каждой группы своя страница "не найдено". Пути заданы один раз в `shared/config/paths.ts`. Роутер использует data API React Router (`createBrowserRouter`): граница ошибок на уровне маршрута, перенаправления через loader и в будущем разделение кода кабинетов через `lazy`. Loader не загружает данные: серверные данные принадлежат TanStack Query. Контроль доступа в интерфейсе не реализован; его обеспечивает сервер. + +`/status` - служебная страница: проверяет `/api/v1/healthz`, ссылка на нее есть только в подвале публичных страниц. Это не показатель готовности продукта. В режиме разработки та же страница показывает галерею состояний на локальных фикстурах (ошибка с повтором, загрузка, пусто, нет доступа, сохранение, уровни доверия); в production-сборку она не попадает. + +## Серверные данные + +Сгенерированные хуки Orval вызывают общий клиент `apiRequest` того же origin, поэтому у `QueryClient` нет функции запроса по умолчанию. Настройки в `app/providers/query-client.ts`: + +- повторы: не больше двух и только при отсутствии ответа (статус 0) и 5xx, кроме 501; 4xx и `invalid_response` завершаются сразу; +- `staleTime` 30 с; фокус окна не перезапрашивает данные, экраны со свежими данными включают это для своего запроса; +- мутации не повторяются, пока API не поддерживает `Idempotency-Key`. + +## Токены и тема + +Токены лежат в `shared/ui/theme/tokens.css`: палитра, семантические цвета, шкала шрифтов, отступы с шагом 4px, радиусы, линии, кольцо фокуса, ширины контента и анимация. Точки перелома зафиксированы в media-запросах: минимум 360px, планшет 768px (`48rem`), навигация для компьютера 1024px (`64rem`) и проверенная широкая ширина 1280px. + +Поставляется только светлая тема. Графитовая боковая панель работодателя - локальная темная область со своими проверенными цветами текста, ссылок и фокуса. Темная тема должна задать и проверить свои пары, а не наследовать светлые акценты. + +Контраст используемых пар по WCAG 2.2: + +| Текст | Фон | Контраст | Где | +| ------- | ------- | -------- | ----------------------------------------- | +| #1B1C21 | #FFFFFF | 17.01 | Текст на поверхностях | +| #1B1C21 | #EDEDED | 14.53 | Текст на фоне страницы | +| #2D2E37 | #FFFFFF | 13.48 | Второстепенный текст | +| #2D2E37 | #EDEDED | 11.52 | Второстепенный текст на фоне страницы | +| #402FFF | #FFFFFF | 6.84 | Ссылки, активная навигация, кольцо фокуса | +| #402FFF | #EDEDED | 5.85 | Метки и ссылки на фоне страницы | +| #FFFFFF | #402FFF | 6.84 | Основная кнопка, ссылка пропуска | +| #EDEDED | #1B1C21 | 14.53 | Текст боковой панели работодателя | +| #FFFFFF | #1B1C21 | 17.01 | Активный пункт и кольцо фокуса в панели | +| #EC1D35 | #FFFFFF | 4.38 | Только графика ошибок (нужно 3:1) | +| #FFFFFF | #EC1D35 | 4.38 | Знак внутри метки ошибки (графика) | + +Исключенные пары: красный не используется для основного текста (4.38 меньше 4.5); #402FFF на #1B1C21 (2.49) и на #2D2E37 (1.97) не используется; серый #C8C9CA (1.66 на белом) - только для декоративных разделителей. + +## Шрифты и логотипы + +JetBrains Mono 2.304 (SIL OFL 1.1) раздается с нашего сервера из `requirements/brandbook/`: файлы woff2 обычного и жирного начертания, текст лицензии и список авторов лежат в `shared/ui/theme/fonts/`. Шрифт применяется через `Mono` для чисел, баллов, кодов и псевдонимов. Для текста используется системный набор шрифтов: Unbounded и Golos Text не добавлены, потому что их файлов и лицензий нет в репозитории. + +В шапке используется логотип ФСП из брендбука без изменений: `logo_02w.svg` на светлом фоне и `logo_01.svg` на графитовой панели, рядом - название продукта. + +## Общие компоненты + +- `Page`, `Section`, `Stack` - раскладка страницы; `Page` содержит единственный `h1` и задает заголовок документа. +- `Button`, `ButtonLink`, `TextLink`, `NavItem` - элементы управления с текстовыми подписями; `NavItem` отмечает активный раздел через `aria-current`, полосу и насыщенность. +- `StatusView`, `LoadingState`, `EmptyState`, `ErrorState`, `ForbiddenState`, `SavingStatus` - состояния экранов. У каждого состояния своя форма и текст. `ErrorState` показывает код, статус, текст сервера и идентификатор запроса как обычный текст и предлагает повтор. +- `QueryView` - превращает результат запроса в загрузку, ошибку, отсутствие доступа (401 и 403 без повтора), пустое состояние или данные. +- `TrustLevel` - пустая метка, кольцо, частичная или полная заливка с видимой подписью. +- `Mono`, `VisuallyHidden`, `SkipLink`, `MainRegion`, `BrandLogo`. + +Доступность: каждая оболочка начинается со ссылки пропуска к `main`, содержит ориентиры и видимое кольцо фокуса и переводит фокус на `main` после перехода. Анимации учитывают `prefers-reduced-motion`. + +## Тесты + +Vitest работает в окружении Node без DOM-библиотеки. Маршруты отрисовываются через статический обработчик React Router и проверяются как HTML: оболочки, ориентиры, ссылка пропуска, активный пункт, перенаправления и страницы "не найдено". Тесты состояний отрисовывают компоненты в разметку; тест ошибки запроса запускает настоящий `QueryClient` со сгенерированной операцией health и подмененным `fetch`. Нажатия и перемещение фокуса проверяются вручную в браузере; автоматические тесты взаимодействия требуют DOM-окружения, а это отдельное решение о зависимости. + Подробнее: [разработка](../docs/ru/DEVELOPMENT.md). diff --git a/frontend/index.html b/frontend/index.html index 9c23cb6..13243c3 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -3,7 +3,7 @@ - + Lincodex diff --git a/frontend/src/app/main.tsx b/frontend/src/app/main.tsx index 49ceaa7..ff915ea 100644 --- a/frontend/src/app/main.tsx +++ b/frontend/src/app/main.tsx @@ -1,6 +1,8 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { App } from "./ui/app"; +import "../shared/ui/theme/fonts.css"; +import "../shared/ui/theme/tokens.css"; import "./ui/styles.css"; const rootElement = document.getElementById("root"); diff --git a/frontend/src/app/providers/query-client.test.tsx b/frontend/src/app/providers/query-client.test.tsx new file mode 100644 index 0000000..0dfcd67 --- /dev/null +++ b/frontend/src/app/providers/query-client.test.tsx @@ -0,0 +1,108 @@ +import { QueryObserver, type QueryObserverResult } from "@tanstack/react-query"; +import { renderToStaticMarkup } from "react-dom/server"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { ApiRequestError, networkErrorCode } from "../../shared/api"; +import { getGetHealthzQueryOptions } from "../../shared/api/endpoints/health/health"; +import type { HealthResponse } from "../../shared/api/schemas"; +import { QueryView } from "../../shared/ui"; +import { createQueryClient, maxQueryRetries, shouldRetryQuery } from "./query-client"; + +afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +function problemResponse(status: number, code: string, traceId: string): Response { + return new Response( + JSON.stringify({ type: `urn:lincodex:problem:${code}`, title: code, status, code }), + { + status, + headers: { "content-type": "application/problem+json", "x-request-id": traceId }, + }, + ); +} + +function healthyResponse(): Response { + return new Response(JSON.stringify({ status: "ok" }), { + headers: { "content-type": "application/json" }, + }); +} + +function renderHealth(result: QueryObserverResult): string { + return renderToStaticMarkup( + {(health) =>

API: {health.status}

}
, + ); +} + +describe("shouldRetryQuery", () => { + const error = (status: number, code: ApiRequestError["code"]) => + new ApiRequestError({ status, code, title: "fixture" }); + + it.each([ + ["no response", error(0, networkErrorCode), true], + ["a server error", error(503, "http_error"), true], + ["an internal error", error(500, "internal"), true], + ["an operation that is not implemented", error(501, "not_implemented"), false], + ["a validation error", error(400, "validation_failed"), false], + ["a missing session", error(401, "unauthenticated"), false], + ["a forbidden request", error(403, "forbidden"), false], + ["rate limiting", error(429, "rate_limited"), false], + ["an invalid response body", error(200, "invalid_response"), false], + ["a programming error", new TypeError("bad path"), false], + ])("retry after %s: %s", (_name, failure, expected) => { + expect(shouldRetryQuery(0, failure)).toBe(expected); + }); + + it("stops after the retry budget", () => { + expect(shouldRetryQuery(maxQueryRetries, error(503, "http_error"))).toBe(false); + }); +}); + +describe("query error and retry through the shared client", () => { + it("shows the error state for a failing request and recovers on retry", async () => { + vi.useFakeTimers(); + const request = vi + .fn() + .mockImplementation(() => Promise.resolve(problemResponse(503, "http_error", "req-503"))); + vi.stubGlobal("fetch", request); + const queryClient = createQueryClient(); + const observer = new QueryObserver(queryClient, getGetHealthzQueryOptions()); + const unsubscribe = observer.subscribe(() => undefined); + + // The first attempt and two automatic retries all fail. + await vi.runAllTimersAsync(); + const failed = observer.getCurrentResult(); + + expect(request).toHaveBeenCalledTimes(1 + maxQueryRetries); + expect(request).toHaveBeenCalledWith("/api/v1/healthz", expect.anything()); + expect(failed.status).toBe("error"); + const errorHtml = renderHealth(failed); + expect(errorHtml).toContain('role="alert"'); + expect(errorHtml).toContain("Сервис временно недоступен"); + expect(errorHtml).toContain("req-503"); + expect(errorHtml).toMatch(/]*>Повторить<\/button>/); + + // The retry button calls refetch on the same query. + request.mockImplementation(() => Promise.resolve(healthyResponse())); + await failed.refetch(); + const recovered = observer.getCurrentResult(); + + expect(recovered.status).toBe("success"); + expect(renderHealth(recovered)).toBe("

API: ok

"); + unsubscribe(); + }); + + it("does not retry a forbidden response and shows the forbidden state", async () => { + const request = vi.fn().mockResolvedValue(problemResponse(403, "forbidden", "req-403")); + vi.stubGlobal("fetch", request); + const queryClient = createQueryClient(); + const observer = new QueryObserver(queryClient, getGetHealthzQueryOptions()); + + await observer.refetch(); + const html = renderHealth(observer.getCurrentResult()); + + expect(request).toHaveBeenCalledTimes(1); + expect(html).toContain("Нет доступа"); + expect(html).not.toContain("= maxQueryRetries || !(error instanceof ApiRequestError)) { + return false; + } + if (error.code === invalidResponseCode) { + return false; + } + return error.status === 0 || (error.status >= 500 && error.status !== 501); +} + +/** + * Server cache for the application. Generated Orval hooks supply each query + * function through the shared same-origin apiRequest client, so there is no + * default query function here. + * + * Window focus does not refetch: cabinets hold forms and long reads where a + * background refetch would flicker states; screens that need fresh data opt + * in per query. Mutations never retry automatically because they are not + * idempotent until the API supports Idempotency-Key. + */ +export function createQueryClient(): QueryClient { + return new QueryClient({ + defaultOptions: { + queries: { + retry: shouldRetryQuery, + staleTime: 30_000, + refetchOnWindowFocus: false, + }, + mutations: { + retry: false, + }, + }, + }); +} diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx new file mode 100644 index 0000000..042e1d2 --- /dev/null +++ b/frontend/src/app/router/routes.test.tsx @@ -0,0 +1,134 @@ +import { QueryClientProvider } from "@tanstack/react-query"; +import { renderToString } from "react-dom/server"; +import { StaticRouterProvider, createStaticHandler, createStaticRouter } from "react-router-dom"; +import { describe, expect, it } from "vitest"; +import { createQueryClient } from "../providers/query-client"; +import { routes } from "./routes"; + +// Node has no DOM in this project's Vitest setup, so routes are rendered +// through React Router's static handler: the same route tree, loaders, and +// layouts as in the browser, checked as server-rendered HTML. +async function render(path: string): Promise { + const handler = createStaticHandler(routes); + const context = await handler.query(new Request(`http://localhost${path}`)); + if (context instanceof Response) { + return context; + } + const router = createStaticRouter(handler.dataRoutes, context); + return renderToString( + + + , + ); +} + +async function renderHtml(path: string): Promise { + const result = await render(path); + if (typeof result !== "string") { + throw new Error(`Expected HTML for ${path}, got a ${result.status} response.`); + } + return result; +} + +function count(html: string, pattern: RegExp): number { + return html.match(new RegExp(pattern.source, "g"))?.length ?? 0; +} + +function currentLinkText(html: string): string[] { + return [...html.matchAll(/]*aria-current="page"[^>]*>(.*?)<\/a>/g)].map( + (match) => match[1] ?? "", + ); +} + +describe("route groups", () => { + it.each([ + ["/", "Протокол подтвержденных навыков", "Публичные разделы"], + ["/login", "Вход", "Публичные разделы"], + ["/register", "Регистрация", "Публичные разделы"], + ["/verify-email", "Подтверждение почты", "Публичные разделы"], + ["/support", "Поддержка", "Публичные разделы"], + ["/candidate", "Главная", "Разделы кабинета кандидата"], + ["/candidate/profile", "Профиль", "Разделы кабинета кандидата"], + ["/candidate/onboarding", "Первые шаги", "Разделы кабинета кандидата"], + ["/employer/company", "Компания и команда", "Разделы кабинета работодателя"], + ["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"], + ])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => { + const html = await renderHtml(path); + + expect(count(html, /]/)).toBe(1); + expect(html).toMatch(new RegExp(`]*>${heading}`)); + expect(html).toMatch(new RegExp(`]*aria-label="${navLabel}"`)); + expect(count(html, /]/)).toBe(1); + expect(html).toMatch(/]*id="main-content"[^>]*tabindex="-1"/i); + expect(html).toContain(`${heading} - Lincodex`); + }); + + it("puts the skip link before any other link and points it at main", async () => { + for (const path of ["/", "/candidate", "/employer/needs"]) { + const html = await renderHtml(path); + const firstLink = html.match(/]*>(.*?)<\/a>/); + + expect(firstLink?.[0]).toContain('href="#main-content"'); + expect(firstLink?.[1]).toBe("Перейти к основному содержимому"); + } + }); + + it("marks the active cabinet section with aria-current", async () => { + expect(currentLinkText(await renderHtml("/candidate"))).toEqual(["Главная"]); + expect(currentLinkText(await renderHtml("/candidate/results"))).toEqual(["Результаты"]); + expect(currentLinkText(await renderHtml("/employer/invitations"))).toEqual(["Приглашения"]); + }); + + it("separates the cabinets: each shell shows only its own navigation", async () => { + const candidate = await renderHtml("/candidate"); + const employer = await renderHtml("/employer/company"); + + expect(candidate).not.toContain("Разделы кабинета работодателя"); + expect(candidate).not.toContain("Публичные разделы"); + expect(employer).not.toContain("Разделы кабинета кандидата"); + expect(employer).not.toContain("Публичные разделы"); + }); + + it("sends the employer cabinet root to the company screen", async () => { + const result = await render("/employer"); + + expect(result).toBeInstanceOf(Response); + expect((result as Response).status).toBe(302); + expect((result as Response).headers.get("Location")).toBe("/employer/company"); + }); + + it.each([ + ["/missing", "/", "На главную"], + ["/candidate/missing", "/candidate", "В кабинет кандидата"], + ["/employer/missing", "/employer/company", "В кабинет работодателя"], + ])("shows a not-found page for %s inside the matching shell", async (path, home, label) => { + const html = await renderHtml(path); + + expect(html).toMatch(/]*>Страница не найдена<\/h1>/); + expect(html).toMatch(new RegExp(`]*href="${home}"[^>]*>${label}`)); + }); +}); + +describe("product readiness", () => { + it("presents the root page as a scaffold, not as a working product", async () => { + const html = await renderHtml("/"); + + expect(html).toContain("Сейчас доступен только каркас интерфейса"); + // The API liveness check lives on the technical page, not on the landing. + expect(html).not.toContain("healthz"); + expect(html).toMatch(/]*href="\/status"[^>]*>Технический статус<\/a>/); + }); + + it("labels the status page as technical", async () => { + const html = await renderHtml("/status"); + + expect(html).toContain("Служебная страница"); + expect(html).toContain("Это не показатель готовности продукта"); + }); + + it("labels every cabinet screen as a placeholder", async () => { + for (const path of ["/candidate", "/candidate/privacy", "/employer/needs"]) { + expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач"); + } + }); +}); diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx new file mode 100644 index 0000000..4aeacd2 --- /dev/null +++ b/frontend/src/app/router/routes.tsx @@ -0,0 +1,89 @@ +import { redirect, type RouteObject } from "react-router-dom"; +import { NotFoundPage } from "../../pages/not-found"; +import { PlaceholderPage } from "../../pages/placeholder"; +import { StatusPage } from "../../pages/status"; +import { WelcomePage } from "../../pages/welcome"; +import { paths } from "../../shared/config"; +import { CandidateShell } from "../../widgets/candidate-shell"; +import { EmployerShell } from "../../widgets/employer-shell"; +import { PublicShell } from "../../widgets/public-shell"; +import { RootLayout } from "../ui/root-layout"; +import { RouteErrorPage } from "../ui/route-error-page"; + +/** + * Route tree with three groups: public pages, the candidate cabinet, and the + * employer cabinet. Each group has its own shell and its own not-found page. + * Access control is not implemented yet; the server will enforce it. + */ +export const routes: RouteObject[] = [ + { + element: , + errorElement: , + children: [ + { + element: , + children: [ + { index: true, element: }, + { path: paths.login, element: }, + { path: paths.register, element: }, + { path: paths.verifyEmail, element: }, + { path: paths.support, element: }, + { path: paths.status, element: }, + { path: "*", element: }, + ], + }, + { + path: paths.candidate.root, + element: , + children: [ + { index: true, element: }, + { + path: paths.candidate.onboarding, + element: , + }, + { path: paths.candidate.profile, element: }, + { + path: paths.candidate.assessment, + element: , + }, + { path: paths.candidate.results, element: }, + { + path: paths.candidate.invitations, + element: , + }, + { path: paths.candidate.privacy, element: }, + { + path: "*", + element: ( + + ), + }, + ], + }, + { + path: paths.employer.root, + element: , + children: [ + // The employer flow starts with the company profile. + { index: true, loader: () => redirect(paths.employer.company) }, + { path: paths.employer.company, element: }, + { path: paths.employer.needs, element: }, + { + path: paths.employer.candidates, + element: , + }, + { + path: paths.employer.invitations, + element: , + }, + { + path: "*", + element: ( + + ), + }, + ], + }, + ], + }, +]; diff --git a/frontend/src/app/ui/app.tsx b/frontend/src/app/ui/app.tsx index c236b31..0e0f6bf 100644 --- a/frontend/src/app/ui/app.tsx +++ b/frontend/src/app/ui/app.tsx @@ -1,24 +1,15 @@ -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { BrowserRouter, Route, Routes } from "react-router-dom"; -import { HomePage } from "../../pages/home"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { RouterProvider, createBrowserRouter } from "react-router-dom"; +import { createQueryClient } from "../providers/query-client"; +import { routes } from "../router/routes"; -const queryClient = new QueryClient({ - defaultOptions: { - queries: { - retry: false, - staleTime: 30_000, - }, - }, -}); +const queryClient = createQueryClient(); +const router = createBrowserRouter(routes); export function App() { return ( - - - } /> - - + ); } diff --git a/frontend/src/app/ui/root-layout.tsx b/frontend/src/app/ui/root-layout.tsx new file mode 100644 index 0000000..95c49dd --- /dev/null +++ b/frontend/src/app/ui/root-layout.tsx @@ -0,0 +1,11 @@ +import { Outlet, ScrollRestoration } from "react-router-dom"; + +/** Top route element shared by every route group. */ +export function RootLayout() { + return ( + <> + + + + ); +} diff --git a/frontend/src/app/ui/route-error-page.tsx b/frontend/src/app/ui/route-error-page.tsx new file mode 100644 index 0000000..98d6243 --- /dev/null +++ b/frontend/src/app/ui/route-error-page.tsx @@ -0,0 +1,24 @@ +import { useRouteError } from "react-router-dom"; +import { ErrorState, Page } from "../../shared/ui"; + +/** + * Last-resort boundary for errors thrown while rendering a route. It has no + * shell, because the shell itself may be what failed. + */ +export function RouteErrorPage() { + const error = useRouteError(); + + return ( +
+ + { + window.location.reload(); + }} + /> + +
+ ); +} diff --git a/frontend/src/app/ui/styles.css b/frontend/src/app/ui/styles.css index 306de26..881d786 100644 --- a/frontend/src/app/ui/styles.css +++ b/frontend/src/app/ui/styles.css @@ -1,32 +1,87 @@ +/* Global base styles. Tokens and fonts are imported before this file. */ :root { - font-family: - Inter, - ui-sans-serif, - system-ui, - -apple-system, - BlinkMacSystemFont, - "Segoe UI", - sans-serif; - color: #15202b; - background: #f4f6f8; + color: var(--color-text); + font-family: var(--font-text); + font-size: 100%; + line-height: var(--line-height-body); + background-color: var(--color-canvas); + color-scheme: light; font-synthesis: none; text-rendering: optimizelegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } -* { +*, +*::before, +*::after { box-sizing: border-box; } body { - min-width: 320px; + min-width: 20rem; min-height: 100vh; margin: 0; + font-size: var(--font-size-m); + + /* Sparse dot grid: a quiet "protocol paper" texture behind surfaces. */ + background-image: radial-gradient(circle at 1px 1px, rgb(27 28 33 / 9%) 1px, transparent 1.5px); + background-size: 1.5rem 1.5rem; +} + +h1, +h2, +h3, +h4, +p, +ul, +ol, +dl, +dd, +figure { + margin: 0; +} + +h1, +h2, +h3, +h4 { + line-height: var(--line-height-snug); + text-wrap: balance; } button, input, +select, textarea { font: inherit; + color: inherit; +} + +img, +svg { + display: block; + max-width: 100%; +} + +/* One focus indicator for every interactive element. Local dark regions + * override --color-focus-ring with a checked value. */ +:focus-visible { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + +:focus:not(:focus-visible) { + outline: none; +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + scroll-behavior: auto !important; + transition-duration: 0.01ms !important; + } } diff --git a/frontend/src/pages/home/index.ts b/frontend/src/pages/home/index.ts deleted file mode 100644 index c0e57bf..0000000 --- a/frontend/src/pages/home/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { HomePage } from "./ui/home-page"; diff --git a/frontend/src/pages/home/ui/home-page.module.css b/frontend/src/pages/home/ui/home-page.module.css deleted file mode 100644 index 1ec8bb2..0000000 --- a/frontend/src/pages/home/ui/home-page.module.css +++ /dev/null @@ -1,54 +0,0 @@ -.page { - display: grid; - min-height: 100vh; - padding: 2rem; - place-items: center; -} - -.panel { - width: min(100%, 38rem); - padding: clamp(1.5rem, 5vw, 3rem); - border: 1px solid #dce3e9; - border-radius: 1.25rem; - background: #fff; - box-shadow: 0 1.5rem 4rem rgb(21 32 43 / 8%); -} - -.status-mark { - display: block; - width: 0.65rem; - height: 0.65rem; - margin-bottom: 1.75rem; - border-radius: 50%; - background: #477a68; -} - -.eyebrow { - margin: 0 0 0.75rem; - color: #52616f; - font-size: 0.8rem; - font-weight: 700; - letter-spacing: 0.08em; - text-transform: uppercase; -} - -.panel h1 { - margin: 0; - font-size: clamp(1.8rem, 5vw, 2.5rem); - letter-spacing: -0.04em; - line-height: 1.15; -} - -.description { - max-width: 31rem; - margin: 1rem 0 0; - color: #52616f; - font-size: 1rem; - line-height: 1.65; -} - -@media (width <= 36rem) { - .page { - padding: 1rem; - } -} diff --git a/frontend/src/pages/home/ui/home-page.tsx b/frontend/src/pages/home/ui/home-page.tsx deleted file mode 100644 index ab2478e..0000000 --- a/frontend/src/pages/home/ui/home-page.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import styles from "./home-page.module.css"; - -export function HomePage() { - return ( -
-
-
-
- ); -} diff --git a/frontend/src/pages/not-found/index.ts b/frontend/src/pages/not-found/index.ts new file mode 100644 index 0000000..f483da2 --- /dev/null +++ b/frontend/src/pages/not-found/index.ts @@ -0,0 +1 @@ +export { NotFoundPage } from "./ui/not-found-page"; diff --git a/frontend/src/pages/not-found/ui/not-found-page.tsx b/frontend/src/pages/not-found/ui/not-found-page.tsx new file mode 100644 index 0000000..ebbeedc --- /dev/null +++ b/frontend/src/pages/not-found/ui/not-found-page.tsx @@ -0,0 +1,29 @@ +import { useLocation } from "react-router-dom"; +import { ButtonLink, Mono, Page } from "../../../shared/ui"; + +type NotFoundPageProps = { + /** Where the recovery link leads, for example the current cabinet. */ + homePath?: string; + homeLabel?: string; +}; + +export function NotFoundPage({ homePath = "/", homeLabel = "На главную" }: NotFoundPageProps) { + const { pathname } = useLocation(); + + return ( + + Адрес {pathname} не ведет ни на один экран. Проверьте ссылку или вернитесь к + началу. + + } + > +
+ {homeLabel} +
+
+ ); +} diff --git a/frontend/src/pages/placeholder/index.ts b/frontend/src/pages/placeholder/index.ts new file mode 100644 index 0000000..2ce492e --- /dev/null +++ b/frontend/src/pages/placeholder/index.ts @@ -0,0 +1,2 @@ +export { PlaceholderPage } from "./ui/placeholder-page"; +export type { ScreenId } from "./model/screens"; diff --git a/frontend/src/pages/placeholder/model/screens.ts b/frontend/src/pages/placeholder/model/screens.ts new file mode 100644 index 0000000..80a56ee --- /dev/null +++ b/frontend/src/pages/placeholder/model/screens.ts @@ -0,0 +1,142 @@ +/** + * Screen map from the product requirements. Each entry is a placeholder + * until its business task implements the real screen; the "planned" lines + * describe intent, not implemented behavior. + */ +export type ScreenArea = "public" | "candidate" | "employer"; + +export type ScreenPlan = { + area: ScreenArea; + title: string; + planned: readonly string[]; +}; + +export const areaLabels: Readonly> = { + public: "Публичный раздел", + candidate: "Кабинет кандидата", + employer: "Кабинет работодателя", +}; + +export const screens = { + login: { + area: "public", + title: "Вход", + planned: ["Вход по почте и паролю", "Восстановление доступа", "Переход в кабинет по роли"], + }, + register: { + area: "public", + title: "Регистрация", + planned: [ + "Выбор сценария: кандидат или работодатель", + "Согласие на обработку персональных данных", + "Письмо для подтверждения почты", + ], + }, + verifyEmail: { + area: "public", + title: "Подтверждение почты", + planned: [ + "Проверка ссылки из письма", + "Повторная отправка письма", + "Понятное сообщение об устаревшей ссылке", + ], + }, + support: { + area: "public", + title: "Поддержка", + planned: [ + "Контакты поддержки", + "Ответы на частые вопросы", + "Как передать идентификатор запроса при ошибке", + ], + }, + candidateHome: { + area: "candidate", + title: "Главная", + planned: [ + "Текущая категория и подтвержденный грейд", + "Следующий шаг по профилю", + "Новые приглашения", + ], + }, + candidateOnboarding: { + area: "candidate", + title: "Первые шаги", + planned: [ + "Согласия и видимость профиля", + "Анкета и ожидаемый грейд", + "Переход к первому тесту", + ], + }, + candidateProfile: { + area: "candidate", + title: "Профиль", + planned: [ + "Специальность и навыки", + "Резюме и достижения ФСП", + "Контакты, скрытые от компаний до приглашения", + ], + }, + candidateAssessment: { + area: "candidate", + title: "Тест", + planned: ["Выбор уровня теста", "Прохождение заданий", "Сохранение ответов"], + }, + candidateResults: { + area: "candidate", + title: "Результаты", + planned: [ + "Подтвержденная категория", + "История попыток и грейдов", + "Разбор результата по компетенциям", + ], + }, + candidateInvitations: { + area: "candidate", + title: "Приглашения", + planned: [ + "Предложения компаний с вилкой зарплаты", + "Принятие или отказ", + "Какие компании получили доступ к контактам", + ], + }, + candidatePrivacy: { + area: "candidate", + title: "Приватность", + planned: ["Видимость профиля в поиске", "Отзыв согласий", "Журнал доступа к контактам"], + }, + employerCompany: { + area: "employer", + title: "Компания и команда", + planned: ["Профиль компании", "Участники и их роли", "Приглашение коллег"], + }, + employerNeeds: { + area: "employer", + title: "Потребности", + planned: [ + "Описание потребности", + "Подтверждение извлеченных навыков", + "Фильтры поиска кандидатов", + ], + }, + employerCandidates: { + area: "employer", + title: "Кандидаты", + planned: [ + "Объяснимая выдача по потребности", + "Шортлист", + "Псевдонимы вместо контактов до принятия приглашения", + ], + }, + employerInvitations: { + area: "employer", + title: "Приглашения", + planned: [ + "Отправленные предложения", + "Статусы: отправлено, просмотрено, принято, отклонено", + "Доступ к контактам после принятия", + ], + }, +} as const satisfies Record; + +export type ScreenId = keyof typeof screens; diff --git a/frontend/src/pages/placeholder/ui/placeholder-page.module.css b/frontend/src/pages/placeholder/ui/placeholder-page.module.css new file mode 100644 index 0000000..0f35319 --- /dev/null +++ b/frontend/src/pages/placeholder/ui/placeholder-page.module.css @@ -0,0 +1,43 @@ +.notice { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-3); + align-items: baseline; + padding: var(--space-4) var(--space-5); + border: var(--line-thin) dashed var(--color-border-strong); + border-radius: var(--radius-m); + background: var(--color-surface); +} + +.tag { + padding: 0 var(--space-2); + border: var(--line-thin) solid var(--color-accent); + border-radius: var(--radius-pill); + color: var(--color-accent); + font-size: var(--font-size-xs); + font-weight: var(--font-weight-bold); + letter-spacing: var(--letter-spacing-label); + text-transform: uppercase; +} + +.plan { + display: grid; + gap: 0; + margin: 0; + padding: 0; + list-style: none; +} + +.plan li { + display: grid; + grid-template-columns: 2.5rem minmax(0, 1fr); + gap: var(--space-3); + padding: var(--space-3) 0; + border-bottom: var(--line-thin) solid var(--color-divider); + font-size: var(--font-size-l); + line-height: var(--line-height-snug); +} + +.plan li > :first-child { + color: var(--color-accent); +} diff --git a/frontend/src/pages/placeholder/ui/placeholder-page.tsx b/frontend/src/pages/placeholder/ui/placeholder-page.tsx new file mode 100644 index 0000000..8aa6d50 --- /dev/null +++ b/frontend/src/pages/placeholder/ui/placeholder-page.tsx @@ -0,0 +1,38 @@ +import { Mono, Page, Section } from "../../../shared/ui"; +import { areaLabels, screens, type ScreenId } from "../model/screens"; +import styles from "./placeholder-page.module.css"; + +type PlaceholderPageProps = { + screen: ScreenId; +}; + +/** + * Honest stand-in for a screen that a later task implements. It names the + * screen and lists what is planned, without imitating working features. + */ +export function PlaceholderPage({ screen }: PlaceholderPageProps) { + const plan = screens[screen]; + + return ( + +

+ Заготовка + Экран будет реализован в одной из следующих задач. Сейчас здесь нет данных и действий. +

+
+
    + {plan.planned.map((item, index) => ( +
  1. + {String(index + 1).padStart(2, "0")} + {item} +
  2. + ))} +
+
+
+ ); +} diff --git a/frontend/src/pages/status/index.ts b/frontend/src/pages/status/index.ts new file mode 100644 index 0000000..0f3bef6 --- /dev/null +++ b/frontend/src/pages/status/index.ts @@ -0,0 +1 @@ +export { StatusPage } from "./ui/status-page"; diff --git a/frontend/src/pages/status/ui/state-fixtures.module.css b/frontend/src/pages/status/ui/state-fixtures.module.css new file mode 100644 index 0000000..ce22b54 --- /dev/null +++ b/frontend/src/pages/status/ui/state-fixtures.module.css @@ -0,0 +1,11 @@ +.success { + display: flex; + flex-wrap: wrap; + gap: var(--space-4); + align-items: center; + justify-content: space-between; + padding: var(--space-5); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-m); + background: var(--color-surface); +} diff --git a/frontend/src/pages/status/ui/state-fixtures.tsx b/frontend/src/pages/status/ui/state-fixtures.tsx new file mode 100644 index 0000000..85eb5ac --- /dev/null +++ b/frontend/src/pages/status/ui/state-fixtures.tsx @@ -0,0 +1,131 @@ +import { useQuery } from "@tanstack/react-query"; +import { ApiRequestError } from "../../../shared/api"; +import { + Button, + EmptyState, + ForbiddenState, + LoadingState, + Mono, + QueryView, + SavingStatus, + Section, + Stack, + TrustLevel, +} from "../../../shared/ui"; +import styles from "./state-fixtures.module.css"; + +const fixtureDelayMs = 600; +let fixtureAttempts = 0; + +function wait(ms: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} + +// Built on demand so production bundles keep no fixture objects. +function forbiddenFixture(): ApiRequestError { + return new ApiRequestError({ + status: 403, + code: "forbidden", + title: "Forbidden", + traceId: "fixture-trace-0002", + }); +} + +// Fails on every odd attempt, so "retry" visibly recovers. +async function flakyFixtureRequest(): Promise<{ attempt: number }> { + fixtureAttempts += 1; + const attempt = fixtureAttempts; + await wait(fixtureDelayMs); + if (attempt % 2 === 1) { + throw new ApiRequestError({ + status: 500, + code: "internal", + title: "Internal server error", + detail: "Fixture failure for the development state gallery.", + traceId: "fixture-trace-0001", + }); + } + return { attempt }; +} + +function FlakyRequestFixture() { + const query = useQuery({ + queryKey: ["dev-fixture", "flaky-request"], + queryFn: flakyFixtureRequest, + retry: false, + staleTime: Infinity, + }); + + return ( + + {(result) => ( +
+

+ Повторный запрос выполнен, попытка {result.attempt}. +

+ +
+ )} +
+ ); +} + +/** + * Development-only gallery of shared states. Every value here is a local + * fixture; nothing comes from the server or proves an API workflow. + */ +export function StateFixtures() { + return ( +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ + + + + +
+
+ + + + + + +
+
+

+ Кандидат K-0427, результат 87 / 100, попытка{" "} + 2 от 14.09.2026. +

+
+
+ ); +} diff --git a/frontend/src/pages/status/ui/status-page.tsx b/frontend/src/pages/status/ui/status-page.tsx new file mode 100644 index 0000000..2fd285e --- /dev/null +++ b/frontend/src/pages/status/ui/status-page.tsx @@ -0,0 +1,20 @@ +import { Page } from "../../../shared/ui"; +import { SystemStatus } from "../../../widgets/system-status"; +import { StateFixtures } from "./state-fixtures"; + +/** + * Service page for developers and operations. It is linked from the public + * footer only and is explicitly not a product readiness indicator. + */ +export function StatusPage() { + return ( + + + {import.meta.env.DEV ? : null} + + ); +} diff --git a/frontend/src/pages/welcome/index.ts b/frontend/src/pages/welcome/index.ts new file mode 100644 index 0000000..4f7b16b --- /dev/null +++ b/frontend/src/pages/welcome/index.ts @@ -0,0 +1 @@ +export { WelcomePage } from "./ui/welcome-page"; diff --git a/frontend/src/pages/welcome/ui/welcome-page.module.css b/frontend/src/pages/welcome/ui/welcome-page.module.css new file mode 100644 index 0000000..bd0d674 --- /dev/null +++ b/frontend/src/pages/welcome/ui/welcome-page.module.css @@ -0,0 +1,79 @@ +.cabinets { + display: grid; + gap: var(--space-4); + margin: 0; + padding: 0; + list-style: none; +} + +.card { + position: relative; + display: grid; + gap: var(--space-2); + padding: var(--space-5); + border: var(--line-thin) solid var(--color-border-strong); + border-radius: var(--radius-l); + color: var(--color-text); + text-decoration: none; + background: var(--color-surface); + transition: + border-color var(--duration-fast) var(--easing-standard), + transform var(--duration-base) var(--easing-standard); +} + +/* Connector node in the corner, echoing the brand line graphics. */ +.card::after { + position: absolute; + top: var(--space-5); + right: var(--space-5); + width: 0.75rem; + height: 0.75rem; + border: var(--line-strong) solid var(--color-accent); + border-radius: 50%; + content: ""; + transition: background-color var(--duration-fast) var(--easing-standard); +} + +.card:hover { + border-color: var(--color-accent); + transform: translateY(-2px); +} + +.card:hover::after { + background: var(--color-accent); +} + +.format { + color: var(--color-accent); + font-size: var(--font-size-xs); + font-weight: var(--font-weight-bold); + letter-spacing: var(--letter-spacing-label); + text-transform: uppercase; +} + +.card-title { + font-size: var(--font-size-xl); + font-weight: var(--font-weight-bold); + line-height: var(--line-height-snug); + text-decoration: underline; + text-decoration-thickness: var(--line-thin); + text-underline-offset: 0.2em; +} + +.summary { + color: var(--color-text-secondary); +} + +.state { + width: fit-content; + padding: 0 var(--space-2); + border: var(--line-thin) dashed var(--color-border-strong); + border-radius: var(--radius-pill); + font-size: var(--font-size-xs); +} + +@media (width >= 48rem) { + .cabinets { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} diff --git a/frontend/src/pages/welcome/ui/welcome-page.tsx b/frontend/src/pages/welcome/ui/welcome-page.tsx new file mode 100644 index 0000000..819dbd8 --- /dev/null +++ b/frontend/src/pages/welcome/ui/welcome-page.tsx @@ -0,0 +1,56 @@ +import { Link } from "react-router-dom"; +import { paths } from "../../../shared/config"; +import { Page, Section, TextLink } from "../../../shared/ui"; +import styles from "./welcome-page.module.css"; + +const cabinets = [ + { + to: paths.candidate.root, + title: "Кабинет кандидата", + format: "Для телефона", + summary: "Профиль, тест, результаты, приглашения и настройки приватности.", + }, + { + to: paths.employer.root, + title: "Кабинет работодателя", + format: "Для компьютера", + summary: "Компания и команда, потребности, подбор кандидатов и приглашения.", + }, +] as const; + +/** + * Public start page. It states plainly that only the interface scaffold + * exists, so it cannot be mistaken for a working product. + */ +export function WelcomePage() { + return ( + +
+
    + {cabinets.map((cabinet) => ( +
  • + + {cabinet.format} + {cabinet.title} + {cabinet.summary} + Пустой каркас + +
  • + ))} +
+
+
+

+ Заготовки: вход,{" "} + регистрация,{" "} + подтверждение почты и{" "} + поддержка. +

+
+
+ ); +} diff --git a/frontend/src/shared/config/index.ts b/frontend/src/shared/config/index.ts new file mode 100644 index 0000000..64cdea6 --- /dev/null +++ b/frontend/src/shared/config/index.ts @@ -0,0 +1 @@ +export { paths } from "./paths"; diff --git a/frontend/src/shared/config/paths.ts b/frontend/src/shared/config/paths.ts new file mode 100644 index 0000000..63cdeab --- /dev/null +++ b/frontend/src/shared/config/paths.ts @@ -0,0 +1,28 @@ +/** + * Route paths shared by the router (app) and navigation (widgets), so a path + * is defined once. Cabinet paths are absolute and nest under their root. + */ +export const paths = { + home: "/", + login: "/login", + register: "/register", + verifyEmail: "/verify-email", + support: "/support", + status: "/status", + candidate: { + root: "/candidate", + onboarding: "/candidate/onboarding", + profile: "/candidate/profile", + assessment: "/candidate/assessment", + results: "/candidate/results", + invitations: "/candidate/invitations", + privacy: "/candidate/privacy", + }, + employer: { + root: "/employer", + company: "/employer/company", + needs: "/employer/needs", + candidates: "/employer/candidates", + invitations: "/employer/invitations", + }, +} as const; diff --git a/frontend/src/shared/ui/.gitkeep b/frontend/src/shared/ui/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/frontend/src/shared/ui/brand/brand-logo.module.css b/frontend/src/shared/ui/brand/brand-logo.module.css new file mode 100644 index 0000000..f4d1ec2 --- /dev/null +++ b/frontend/src/shared/ui/brand/brand-logo.module.css @@ -0,0 +1,45 @@ +.root { + display: inline-flex; + gap: var(--space-3); + align-items: center; + min-height: 2.75rem; + border-radius: var(--radius-s); + text-decoration: none; +} + +.logo { + width: auto; + height: 1.75rem; +} + +.divider { + align-self: stretch; + width: var(--line-thin); + margin-block: var(--space-2); + background: currentcolor; + opacity: 0.4; +} + +.name { + display: grid; + font-size: var(--font-size-m); + font-weight: var(--font-weight-bold); + letter-spacing: -0.01em; + line-height: 1.1; +} + +.context { + font-size: var(--font-size-xs); + font-weight: var(--font-weight-medium); + letter-spacing: 0; +} + +/* Graphite on white 17.01:1. */ +.light { + color: var(--color-text); +} + +/* Light grey on graphite 14.53:1. */ +.dark { + color: var(--palette-light); +} diff --git a/frontend/src/shared/ui/brand/brand-logo.tsx b/frontend/src/shared/ui/brand/brand-logo.tsx new file mode 100644 index 0000000..7382179 --- /dev/null +++ b/frontend/src/shared/ui/brand/brand-logo.tsx @@ -0,0 +1,36 @@ +import { Link } from "react-router-dom"; +import logoOnDark from "./fsp-logo-on-dark.svg"; +import logoOnLight from "./fsp-logo-on-light.svg"; +import styles from "./brand-logo.module.css"; + +type BrandLogoProps = { + /** Background the logo sits on; selects the brandbook color variant. */ + tone?: "light" | "dark"; + /** Destination of the home link. */ + to?: string; + /** Cabinet name shown after the product name. */ + context?: string | undefined; +}; + +/** + * Brandbook FSP logo (logo_02w for light, logo_01 for dark backgrounds) + * followed by the product name. The whole block is one link home. + */ +export function BrandLogo({ tone = "light", to = "/", context }: BrandLogoProps) { + return ( + + ФСП +