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." ), ]