Files
lincodex/api/README.en.md
T

165 lines
22 KiB
Markdown

# API contracts
[Русский](README.md) | English
Shared OpenAPI contracts for Go, the frontend, and ML. Contract changes come first; consumers then generate their types, server code, and clients from them.
- `core/` defines the main backend's public API.
- `ml/` defines the ML service's internal HTTP API.
- `testdata/` contains a specification for checking tool compatibility with OpenAPI 3.2.0.
Routes live in `routes/` and schemas in `components/`. The `openapi.bundle.yml` files are built automatically. Generator configuration lives in `backend/codegen/`, `frontend/codegen/`, and `ml/codegen/`.
From the repository root, `make -C api check` checks contracts and `make generate` updates all generated code.
## Contract conventions
`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation requires Idempotency-Key, but no operation stores keys yet.
### Errors
Every error is an RFC 9457 problem with the `application/problem+json` media type and the `Problem` schema. Required fields are `type` (`urn:lincodex:problem:<code>`), `title`, `status`, and `code`; optional ones are `detail`, `instance`, `trace_id` (equal to the `X-Request-ID` response header), and `errors`. Clients branch on `code`. Titles and details are fixed per code and never contain internal error text, stack traces, credentials, contact data, or submitted values.
| Code | Status | Meaning |
| --- | --- | --- |
| `validation_failed` | 400 | Parameters or body do not match the contract, or the body violates a domain rule; `errors` lists the fields |
| `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 |
| `state_conflict` | 409 | The operation is not allowed in the current state of the resource |
| `version_conflict` | 412 | If-Match does not match the current version |
| `payload_too_large` | 413 | The body exceeds the operation limit |
| `unsupported_media_type` | 415 | The request Content-Type is not accepted |
| `idempotency_key_reused` | 422 | The Idempotency-Key was used with a different request |
| `precondition_required` | 428 | The operation requires If-Match |
| `rate_limited` | 429 | Too many requests; see `Retry-After` |
| `internal` | 500 | Unexpected server error |
| `not_implemented` | 501 | The operation is in the contract but not implemented |
Request validation uses 400 rather than 422. The generated ogen server reports malformed and schema-invalid parameters and bodies through the same decoding errors, and for parameters it does not separate syntax from schema violations; one status keeps client handling uniform. 422 then stays free for Idempotency-Key reuse, as the IETF Idempotency-Key header draft recommends. Domain rules on the body, such as `salary_from <= salary_to`, also answer 400 `validation_failed` with body pointers to the fields involved. Each `errors` item has `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` in the body, an empty string for the whole body, `/limit` for a parameter), `code` (`required` or `invalid`; clients tolerate new values), and a fixed `message`. When the decoder does not record the path of a nested body field, the pointer is the whole body. A body cut by an `http.MaxBytesReader` limit answers 413 `payload_too_large`.
`state_conflict` covers business state conflicts, such as accepting an invitation that was already withdrawn. `idempotency_in_progress` is reserved for concurrent retries; the reusable responses are `StateConflict` and `IdempotencyInProgress`.
Every operation declares `default: $ref: ../components/responses.yml#/Problem`; ogen then generates a single error type. An operation adds a specific response (for example `PreconditionFailed`) when clients need it in the generated types. In the Go API, unknown paths under `/api`, including paths outside `/api/v1`, answer 404 `not_found`, and a panic in an operation answers 500 `internal`; only the panic type and stack are logged.
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.
The server checks in this order:
1. Authentication (401), request validation (400, 413, 415), and authorization (403). Nothing is recorded for the key.
2. A stored or running request with the same key and a different fingerprint: 422 `idempotency_key_reused`. This check comes before the in-progress check.
3. A running request with the same key and fingerprint: 409 `idempotency_in_progress`; retry later.
4. A stored outcome with the same key and fingerprint: the outcome is replayed.
5. If-Match (428, 412), then the command itself; a storable outcome is recorded.
Because the replay check comes before If-Match, a retry of a completed change replays its outcome instead of failing on the version that the change itself advanced. A missing or malformed key returns 400 `validation_failed` with the pointer `/Idempotency-Key`. After 24 hours the key may be accepted as new.
### Versions: ETag and If-Match
A response with a versioned resource returns a strong `ETag`, for example `"v7"`. An operation that changes such a resource says in its description that it requires `If-Match` with that value. A missing value returns 428 `precondition_required`; a value that does not equal the current ETag returns 412 `version_conflict` and changes nothing. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. Weak tags, lists, and `*` fail validation with 400.
### Pagination
Lists use cursor pagination: `limit` from 1 to 100 (20 by default) and an opaque `cursor` of up to 512 characters `A-Z a-z 0-9 _ -`. The response holds the items in a bounded array and `page` (`PageInfo`) with `has_more` and `next_cursor`, which is null on the last page. A malformed cursor returns 400 `validation_failed`.
### Time and money
Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with the `Z` suffix (RFC 3339). Servers always emit UTC. ogen generates `Timestamp` as a named Go type over `time.Time`; call `.UTC()` where a value is converted to it. Money is planned as an integer number of whole rubles with explicit fields for the base, such as the pay period and gross or net; the schema is added with the first business field that carries money.
### ML service errors
The ML service answers its errors with the same `Problem` schema. 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. These lifetimes come from the versioned product policy (demo version 1 of the `product` family), not from configuration; see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#product-policy-versions).
- Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check.
- The verification link is `<frontend origin>/verify-email#token=<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. Both come from the versioned product policy, not from configuration.
- The `sessionCsrf` scheme is the `X-CSRF-Token` header with the session-bound token from `Session.csrf_token`. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`.
- Every unsafe request, including the public ones, must carry an `Origin` from the configured allowlist, otherwise 403 `csrf_check_failed` (planned, TASK-056; see the [development guide](../docs/en/DEVELOPMENT.md#sessions-on-local-http)). Public identity operations are rate-limited (429 with `Retry-After`).
- Responses with a session or account carry `Cache-Control: no-store`.
- 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
`testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core.
`make -C api check-toolchain` lints the fixture and runs the three generators on it; it needs the backend Go toolchain, pnpm, and uv, so pass the same `UV` override as for `make generate`.
| Target | Generator | Exercised conventions |
| --- | --- | --- |
| `make -C backend check-ogen-compat` | ogen | All of them: Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch, ETag. Its tests check validation errors, the retry scenario, the preconditions, and the 413 body limit against the backend problem mapping |
| `make -C frontend check-orval-compat` | Orval | Problem, PageInfo, Timestamp, PageLimit, PageCursor, IdempotencyKey, IfMatch. The output is type-checked with the frontend compiler settings |
| `make -C ml check-pydantic-compat` | datamodel-code-generator | Problem, PageInfo, Timestamp, PageLimit, PageCursor. The models pass `mypy --strict` and a validation script |
Each target writes its output to a temporary directory and removes it.
Known generator limitations:
- Orval 8.40 writes no Zod schema for `components/responses` but imports a `<Name>Response` type for each reference. `frontend/codegen/orval.config.ts` therefore inlines response references before generation.
- Orval passes header parameters as a typed argument only with `headers: true`. With `exactOptionalPropertyTypes`, an optional header such as `If-Match` fits `RequestInit` only when Zod emits exact optional properties, so the configuration also sets `override.zod.exactOptional`.
- Orval generates no type for response headers, and `apiRequest` returns only the body, so a generated client cannot read `ETag` yet. The first operation with a versioned resource must expose it, for example through the response body or the mutator.
- datamodel-code-generator 0.83.0 generates models only for schemas and query and path parameters; header parameters and response headers (Idempotency-Key, If-Match, ETag) produce no Python model.
- Orval does not generate `additionalOperations` methods.
- ogen writes the header name in its canonical Go form (`Etag`); HTTP header names are case-insensitive.
- 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).